2016-09-20 3 views
1

Я пытаюсь прочитать файл excel (.xlsx) в приложении Visual Studio Windows с использованием C#. Я использую Google Excel Library по этой ссылке ExcelLibrary. Я использовал следующий код для чтения из файла excel при нажатии кнопки. Я использую следующий код в Visual Studio 2012 Professional,OutOfMemoryException при чтении файла Excel .xlsx в C# с использованием ExcelLibrary

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 

Файл первенствовать я попытка читать только 18 КБ, поэтому из памяти даже не возможно. Я не уверен, почему я получаю это исключение.

+0

Меня беспокоят те петли. Какую строку он получает и вызывает ошибку? – KSib

+0

@KSib im получение '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», вы должны использовать ссылки «Microsoft.Office.Interop.Excel» и «Office» из GAC.

Они должны быть уже установлены на вашем компьютере, если у вас уже установлен Microsoft Office на вашем компьютере.

Смежные вопросы