使用Microsoft.Office.Interop.Excel从excel 2010中读取数据
本文关键字:2010 读取 数据 excel Microsoft Office Interop Excel 使用 | 更新日期: 2023-09-27 18:08:04
我无法在Excel中读取数据。下面是我使用的代码:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"Book1.xlsx", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "'t", false, false, 0, true, 1, 0);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
MessageBox.Show(xlWorksheet.Cells[i,j].ToString());
}
}
我得到一个关于System.__ComObject
的消息框,而不是一个值。
我该如何解决这个问题?
我找到了上面的解决方案,下面是代码:
string temp = (string)(xlRange.Cells[i, j] as Excel.Range).Value2;
MessageBox.Show(temp);
还没有测试过,但我认为应该是
MessageBox.Show(xlRange.Cells[i,j].ToString());
或
MessageBox.Show(xlRange.Cells[i,j].Value.ToString());
试试这个:
MessageBox.Show(xlRange.Cells[i][j].Value);
使用以下函数获取数据作为第N个表的DATATABLE对象:
public DataTable GetWorkSheet(int workSheetID)
{
string pathOfExcelFile = fileFullName;
DataTable dt = new DataTable();
try
{
excel.Application excelApp = new excel.Application();
excelApp.DisplayAlerts = false; //Don't want Excel to display error messageboxes
excel.Workbook workbook = excelApp.Workbooks.Open(pathOfExcelFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //This opens the file
excel.Worksheet sheet = (excel.Worksheet)workbook.Sheets.get_Item(workSheetID); //Get the first sheet in the file
int lastRow = sheet.Cells.SpecialCells(excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row;
int lastColumn = sheet.Cells.SpecialCells(excel.XlCellType.xlCellTypeLastCell, Type.Missing).Column;
excel.Range oRange = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[lastRow, lastColumn]);//("A1",lastColumnIndex + lastRow.ToString());
oRange.EntireColumn.AutoFit();
for (int i = 0; i < oRange.Columns.Count; i++)
{
dt.Columns.Add("a" + i.ToString());
}
object[,] cellValues = (object[,])oRange.Value2;
object[] values = new object[lastColumn];
for (int i = 1; i <= lastRow; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
values[j] = cellValues[i, j + 1];
}
dt.Rows.Add(values);
}
workbook.Close(false, Type.Missing, Type.Missing);
excelApp.Quit();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message, "Error", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
return dt;
}
试试下面的代码:
MessageBox.Show(((Excel.Range)xlRange.Cells[i,j]).Value2.ToString());