我正在尝试使用C#在Visual studio Windows应用程序中读取excel文件(.xlsx)。我正在使用这个链接ExcelLibrary中的Google Excel Library。我使用下面的代码在点击按钮时从excel文件中读取。我在Visual Studio 2012 Professional中使用以下代码,
using ExcelLibrary.SpreadSheet;
using ExcelLibrary.BinaryDrawingFormat;
using ExcelLibrary.BinaryFileFormat;
using ExcelLibrary.CompoundDocumentFormat;
namespace ExcelRead
{
public partial class ReadForm : Form
{
public ReadForm()
{
InitializeComponent();
}
private void btnRead_Click(object sender, EventArgs e)
{
WorkBook inputBook = Workbook.Load("D:\\Files\\input.xlsx");
List<Worksheet> sheetList = inputBook.Worksheets;
for (int i = 0; i < sheetList.Count; i++)
{
Worksheet sheet = inputBook.Worksheets[i];
for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
Console.WriteLine(cell.ToString());
}
}
}
}
}
}但当我运行代码并单击按钮时,它会提供OutOfMemoryException was unhandled异常。它在异常中显示以下描述。
An unhandled exception of type 'System.OutOfMemoryException' occurred in mscorlib.dll我试着像下面这样使用try-catch,
try
{
WorkBook inputBook = Workbook.Load("D:\\Files\\input.xlsx");
List<Worksheet> sheetList = inputBook.Worksheets;
for (int i = 0; i < sheetList.Count; i++)
{
Worksheet sheet = inputBook.Worksheets[i];
for (int rowIndex = sheet.Cells.FirstRowIndex; rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
{
Row row = sheet.Cells.GetRow(rowIndex);
for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
{
Cell cell = row.GetCell(colIndex);
Console.WriteLine(cell.ToString());
}
}
}
}
catch (Exception err)
{
Console.WriteLine(err);
}但它再次显示以下错误,
Adding a 'catch clause' around an active statement will prevent the debug session from continuing while Edit and Continue is enabled我试图读取的excel文件只有18KB,所以内存不足甚至是不可能的。我不确定为什么我会得到这个异常。
发布于 2016-09-21 03:53:06
由于您使用的是".xlsx“文件,因此应该使用来自GAC的"Microsoft.Office.Interop.Excel”和"Office“引用。
假设您的计算机上已经安装了Microsoft Office,则应该已经在计算机上安装了这些软件。
https://stackoverflow.com/questions/39602070
复制相似问题