我正在尝试使用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,因此甚至无法使用内存不足。我不知道为什么我会得到这个例外。
答案 0 :(得分:2)
由于您使用的是“.xlsx”文件,因此应使用GAC的“Microsoft.Office.Interop.Excel”和“Office”引用。
假设您的计算机上已安装Microsoft Office,这些应该已经安装在您的计算机上。