I’m trying to import tariff information from an Excel file into a DataTable to bind to a GridView. I’m limited to 2003 right now, and for the foreseeable future. From what I gather there are two methods.
One querying the excel sheet using ADO SELECT Code, Description FROM [Sheet1$]
With this connection string Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\file.xls;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\
Problem with this: Jet for some reason truncates the cell length at 255 characters. The tariff descriptions can be around 900 sometimes. I’ve read into this, and can’t seem to find a solution. Some people say it’s because the description is stored as Text and not Memo, but I can’t seem to fix it.
OR
The other solution I’ve found is using Microsoft.Office.Interop.Excel. It works and grabs all of the Description field, but the code is very ugly. It runs through each cell of each row of the worksheet and copies the text value into a DataRow, then appends it onto a DataTable.
// Set Columns
for (int i = 1; i <= columnCount; i++) {
Range columnRange = (Range)oSheet.Cells[1, i];
dt.Columns.Add(columnRange.Text.ToString());
}
// Add Rows
for (int i = 2; i <= rowCount; i++) {
dr = dt.NewRow();
for (int j = 1; j <= columnCount; j++) {
oRng = (Range)oSheet.Cells[i, j];
dr[j - 1] = oRng.Text.ToString().Trim();
}
Problem with this: very slow, cause of the nested loop.
Is there a faster way to get the data into a DataTable using Interop? Or a way to prevent the truncation of 255 characters using the query?
You could have a look at the Excel Data Reader library. I’ve had pretty good luck with it and I think it will do what you’re looking for pretty easily.