Error in reading an uploaded .xls excel file in asp.net
I have made a program where I read set of records from the database and then save it in a datagrid. From here I make the user download the file as a excel file.
Now the user make changes to the file and then upload it again and from here I read the uploaded .xls file and make the necessary changes in the DB.
The problem is whenever the user is uploading the updated excel file, I cannot access it and get an error.
External table is not in the expected format
I make the user download the file as
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (System.IO.StringWriter sw = new System.IO.StringWriter())
开发者_如何学编程 {
using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw))
{
// instantiate a datagrid
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
The user upload the file after making changes and I am reading it as
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + path + "\\" + FileUpload1.FileName + ";Extended Properties=Excel 8.0;";
OleDbConnection oledbConn = new OleDbConnection(connString);
oledbConn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [$Sheet1 ", oledbConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Employees");
Kindly help. Thanks.
Is it possible that the version of XLS file that you are generating cannot be read by OLEDB? Excel 8 is Excel 97 and you will likely be generating an Excel 2007 .xlsx format.
Yes i agree to brian! you might be generating a different .xlsx format that you wants to read.
Try this: http://www.aspdotnet-suresh.com/2010/09/import-data-from-excel-to-sql-database.html
精彩评论