|
|||||||||||||||
|
Getting Started
In this page you'll find some brief tutorials to get started with NExcel.
Here is a list of the tutorials:
Reading Contents from a Excel file is a "Hello World" example, useful if you are new
to NExcel.
Reading Values from a Excel file does the same, but with values.
Reading Contents from a Excel file
This example explains how you can read cell contents of a Excel file using C# and NExcel.
Cell content is the layout text a user can see in a cell using Ms Office Excel. It usually differs from inner value of cells. For instance, consider a number cell with 2 digits and set to value 6534.1234. The cell will contain inner value 6534.1234 and will show the content "6534.12". In NExcel you get the cell contents using property Cell.Contents. This property returns a string. If cell is empty, it returns "".
Now let's see how using Cell.Contents in our code.
using NExcel; Open the Excel file with name filename using method Workbook.getWorkbook() and assign the result to workbook. Get each sheet from workbook.Sheets and assign it to sheet. // open the Excel workbook Workbook workbook = Workbook.getWorkbook(filename); // for each sheet in workbook, write cell contents to console foreach (Sheet sheet in workbook.Sheets) { ...... Get all cells in sheet, iterating for each row and column. // for each row for (int irow = 0; irow < sheet.Rows; irow++) { // for each column for(int icol=0; icol < sheet.Columns; icol++) { // get current cell Cell cell = sheet.getCell(icol, irow); .....
Now, get contents of cell using property Cell.Contents and write the result to console.
// write to console the cell contents System.Console.WriteLine("{0}[{1},{2}]: {3}", sheet.Name, irow, icol, cell.Contents); At the end, close the workbook with workbook.close(). workbook.close(); Reading Values from a Excel file
This example explains how read cell values of a Excel file using C# and NExcel.
Cell value is the inner data of a cell. Cell value is more reliable than contents, because it doesn't depend on cell format. In NExcel you get the cell value using property Cell.Value. This property returns a object, which can be a double for numeric cells, a DateTime for date cells, a string for text cells and so on for other cells.
Now let's see how using Cell.Value in our code.
Now get the cell value with Cell.Value and write it to console. If it is null is changed to "". // get value as string string strValue = (cell.Value!=null) ? cell.Value.ToString() : ""; // write to console the cell value System.Console.WriteLine("{0}[{1},{2}]: {3}", sheet.Name, irow, icol, strValue); You'll see that cells of different type return values of different type. Number cells return a double, date cells and time cells a DateTime object, text cells a string and empty cells a null.
|
||||||||||||||
|
|||||||||||||||
Copyright © 2005 Stefano Franco
|