Im trying that, user select excel file from uploadcontrol and upload or show me full path/directory of file because i will parse file and update to datatable .
my import to datable code at below , how i solve this situation
project developing with asp.net 4.0 ,c#
public DataTable Import(String path){
Microsoft.Office.Interop.Excel.ApplicationClass app = new Microsoft.Office.Interop.Excel.ApplicationClass();
Microsoft.Office.Interop.Excel.Workbook workBook = app.Workbooks.Open(path, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet;
int index = 0;
object rowIndex = 2;
DataTable dt = new DataTable();
dt.Columns.Add("FirstName");
dt.Columns.Add("开发者_运维技巧LastName");
dt.Columns.Add("Mobile");
dt.Columns.Add("Landline");
DataRow row;
while (((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2 != null)
{
rowIndex = 2 + index;
row = dt.NewRow();
row[0] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 1]).Value2);
row[1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 2]).Value2);
row[2] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 3]).Value2);
row[3] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[rowIndex, 4]).Value2);
index++;
dt.Rows.Add(row);
}
app.Workbooks.Close();
return dt;
}
As Svick says, you did not really ask a question, but in the mean time you might want to investigate reading from Excel using ADO.Net, which will let you create a dataset from an Excel sheet in just a few steps. Or maybe one of the third-party components out there that read/write Excel sheets are something for you (Flexcel and Gembox spring to my mind). All with the advantage that you do not need to have Excel installed at the computer where your application runs. (See Mathias's remark).
With GemBox.Spreadsheet you can very easily accomplish this task.
Here is an example Excel C# code:
ExcelFile ef = new ExcelFile();
ef.LoadXls(path);
DataTable dt = ef.Worksheets[0].CreateDataTable(ColumnTypeResolution.Auto);
return dt;
精彩评论