2013-03-07 41 views
0

我需要一些快速幫助。 如何使用excellibrary獲取單元格的內容?文檔非常薄。C#Excellibrary - 如何獲取單元格內容?

我真的不明白示例代碼:

// traverse cells 
foreach (Pair<Pair<int, int>, Cell> cell in sheet.Cells) 
{ 
    dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value; 
} 

// traverse rows by Index 
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); 
    } 
} 

這似乎過於複雜。 我需要做的是這樣的:

xlInfo[0,0] = cell 1,1; 
xlInfo[0,1] = cell 1,2; 
xlInfo[0,2] = cell 1,3; 

隨着EPPlus它會是這個樣子:

xlInfo[0,0] = sheet.Cells[1,1]; 
xlInfo[0,1] = sheet.Cells[1,2]; 
xlInfo[0,2] = sheet.Cells[1,3]; 

是否與excellibrary這樣做的一個類似的方式? (免責聲明:可能會發生一些語法錯誤在這些示例代碼片段,但他們只是在那裏理論的目的。)

編輯:

xlInfo[0, 0] = Convert.ToString(sheet.Cells[1, 1]); 

讓我不設置到一個NullReferenceException(對象引用對象的實例)。

我使用:http://code.google.com/p/excellibrary/

+0

你的意思是Excel Interop? – MoonKnight 2013-03-07 09:21:36

+0

而不是掙扎着,爲什麼不嘗試使用另一個庫,http://exceldatareader.codeplex.com/也許? – andri 2013-03-07 09:38:31

+0

我急於完成這段代碼,忽略了一個簡單的事實。我在我的xlInfo [,]中有一個錯誤。工作正常。我應該刪除這個問題嗎? – 2013-03-07 09:40:52

回答

1

這個工作初始化數組後精(忘了初始化它帶來了,我誤以爲關於ExcelLibrary一個錯誤的錯誤)。

Workbook book = Workbook.Load(directory + "file.xls"); 
Worksheet sheet = book.Worksheets[0]; 
xlInfo = new string[sheet.Cells.LastRowIndex, 3]; 

xlInfo[0, 0] = Convert.ToString(sheet.Cells[1, 0]); 
xlInfo[0, 1] = Convert.ToString(sheet.Cells[1, 1]); 
xlInfo[0, 2] = Convert.ToString(sheet.Cells[1, 2]); 
相關問題