1
我想使用C#
在Visual Studio Windows應用程序中讀取Excel文件(.xlsx)。我正在使用此鏈接ExcelLibrary中的Google Excel Library
。我使用下面的代碼從excel文件中讀取按鈕單擊。我用下面的代碼在Visual Studio 2012專業版,使用ExcelLibrary在C#中讀取Excel .xlsx文件時出現OutOfMemoryException
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
@KSib即時獲得'OutofMemoryException'在這一行 'WorkBook inputBook = Workbook.Load(「D:\\ Files \\ input.xlsx」);' –
什麼版本的Office是用這個文件創建的?根據文檔xlsx格式甚至還不支持(還):目前.xls(BIFF8)格式被實現。將來,.xlsx(Excel 2007)也可能受支持。請參閱https://code.google.com/archive/p/excellibrary/ –