在c#中使用ExcelLibrary读取Excel .xlsx文件时出现OutOfMemoryException
本文关键字:文件 xlsx OutOfMemoryException Excel 读取 ExcelLibrary | 更新日期: 2023-09-27 18:07:53
我正在尝试使用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文件只有18 KB,所以内存不足是不可能的。我不知道为什么我得到这个异常
由于您使用的是".xlsx"文件,因此您应该使用"Microsoft.Office.Interop. "Excel"answers"Office"参考资料来自GAC。
这些应该已经安装在您的计算机上,假设您的计算机上已经安装了Microsoft Office。