2016-09-20 121 views
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,因此内存不足甚至不可能。我不知道为什么我得到这个例外。

+0

我很关心那些循环。哪条线路出现并导致错误? – KSib

+0

@KSib即时获得'OutofMemoryException'在这一行 'WorkBook inputBook = Workbook.Load(“D:\\ Files \\ input.xlsx”);' –

+0

什么版本的Office是用这个文件创建的?根据文档xlsx格式甚至还不支持(还):目前.xls(BIFF8)格式被实现。将来,.xlsx(Excel 2007)也可能受支持。请参阅https://code.google.com/archive/p/excellibrary/ –

回答

1

由于您使用的是“.xlsx”文件,因此应使用GAC的“Microsoft.Office.Interop.Excel”和“Office”参考。

这些应该已经安装在您的计算机上,假定您的计算机上已经安装了Microsoft Office。

相关问题