在C#中读取Excel文件总是导致System.__ComObject出现?

3

这是我用来读取xls文件的代码:

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(1);

MessageBox.Show(excelSheet.Cells[1,1].ToString());

这将导致一个带有以下信息的消息框:

System.__ComObject

不确定发生了什么事情,非常感谢任何帮助,谢谢!

3个回答

4
使用范围
Microsoft.Office.Interop.Excel.Range range =(Microsoft.Office.Interop.Excel.Range)excelSheet.Cells[1,1];
string cellValue =range.Value.ToString();

3
在你的例子中,excelSheet.Cells[1,1] 不是一个值,而是一个对象(Range)。你需要获取该对象的 Value 属性。
MessageBox.Show(excelSheet.Cells[1, 1].Value.ToString());

0

在我的项目中我使用Value2:

 MessageBox.Show(((Microsoft.Office.Interop.Excel.Range)excelSheet.Cells[1, 1]).Value2.ToString());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接