I need to get data from an Excel file to print them in a HTML table (using MVC, no gridview) and eventually store them in a Database.
The mapping between table and Excel is as follows:
Excel -> Table
First Row -> Table headers
Other Cells -> Table data
I am using the Interop.Excel library that provides methods to manipulate Excel files in .NET.
With this code I obtain in lworkSheet variable the Nth worksheet of the Excel file:
var lworkSheet = xlWorkBook.Worksheets.get_Item(N);
Let's assume the Excel file has just one worksheet (N = 1), I can use worksheet specific properties to get Rows, Columns, Cells and Range. These properties return objects of type Interop.Excel.Range.
The problem is that Rows, Columns and Cells return, respectively, all the rows, columns and cells in the Excel file not just those that are filled with data. Therefore in order to get the data I do (the index of the Excel items are 1-based):
var lheaders = xlWorkSheet.Rows.get_Item(1);
var lexcelItems = new Excel.Range[xlWorkSheet.Rows.Count, xlWorkSheet.Columns.Count];
for (var i=0; i < xlWorkSheet.Rows.Count; i++)
{
for(var j=0; j < xlWorkSheet.Columns.Count; j++)
{
lexcelItems[i,j] = xlWorkSheet.Cells.get_Item(i+2, j+1);
}
}
Besides the computational waste of cycling all rows and columns, these solution is still not acceptable because the get_Item() method returns Range objects!! In order to get the item in the cell I have to use the get_Range(cell_start, cell_end) method and specify the cells in the "A1", "A2", etc... format.
QUESTIONS:
1) Any way to identify last item in row and column?
2) Any way to get the value in the cell without specify the range?
3) Any library that implements the Excel.Range increment? (i.e. (A1++) == A2, etc...).
4) If none of the above is feasible, is there an easy way to read Excel with OLEDB?
Thanks
Francesco