Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Importing data from an Excel file

Hello there,

I'm creating a web site using C# in visual studdio. I want to import data from an excel file to a SQL Server database.

I'm using the following code to open the excel file and read the data from cell A1 into a label:

protected void btnUpload_Click(object sender, EventArgs e)
{
Excel.Application excelApp = new Excel.ApplicationClass();
Excel.Workbook newWorkbook =excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);

string workbookPath = "c:/test.xls";
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "", false, false, 0, true, false, false);

Excel.Sheets excelSheets = excelWorkbook.Worksheets;

string currentSheet = "Sheet1";
Excel.Worksheet excelWorksheet =(Excel.Worksheet)excelSheets.get_Item(currentSheet);

Excel.Range excelCell =(Excel.Range)excelWorksheet.get_Range("A1", "A1");

lblTitle.Text = excelCell.Value2.ToString();

}

However i want to read in multiple values from the workbook and write them to my database.

Any ideas as to how i go about this?

I was thinking of maybe reading the values into a gridview and writing them to the database from there. Not exactly sure how to do thiis though.

Any help would be much appreciated,

Thanks,

Adrian
[1413 byte] By [admol] at [2007-11-11 10:23:51]
# 1 Re: Importing data from an Excel file
why not instead of changing the text of a label, while looping through the data build an INSERT sql statement on each iteration.

i.e.

loop through data{

sql += "INSERT INTO myTable (item1, item2, item3) values (val1, val2, val3); ";

}

then run the sql statement on the connection to the database.

ideally though, to save on bandwidth and make it easier to maintain my suggestion would be having a stored procedure to do this..

Im not sure about the datagridview, never used one, sorry!

-Dan
djbyrne at 2007-11-11 20:47:54 >