【发布时间】:2017-01-28 20:22:45
【问题描述】:
我正在尝试使用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,因此内存不足甚至是不可能的。我不确定为什么会出现此异常。
【问题讨论】:
-
我很担心这些循环。它到达哪一行并导致错误?
-
@KSib 我在这一行得到
OutofMemoryExceptionWorkBook inputBook = Workbook.Load("D:\\Files\\input.xlsx"); -
用什么版本的 Office 创建文件?根据文档,甚至不支持 xlsx 格式(尚):目前已实现 .xls (BIFF8) 格式。将来也可能支持 .xlsx (Excel 2007)。见code.google.com/archive/p/excellibrary
-
@DangerZone 是的,我也尝试打开一个包含一行的简单文件,但它不起作用,显示相同的错误。
-
这很奇怪。我还担心该存储库的最后提交日期(2013 年),因为它不再受支持。可能只是太多行、太多公式等的错误。您是否尝试过使用更新的库(例如 EPPlus)? epplus.codeplex.com
标签: c# asp.net excel windows forms