簡體   English   中英

使用 ExcelLibrary 在 C# 中讀取 Excel .xlsx 文件時出現 OutOfMemoryException

[英]OutOfMemoryException when reading Excel .xlsx file in C# using ExcelLibrary

我正在嘗試使用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”文件,因此您應該使用 GAC 中的“Microsoft.Office.Interop.Excel”和“Office”引用。

假設您的計算機上已經安裝了 Microsoft Office,這些應該已經安裝在您的計算機上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM