在asp.net中读取上传的.xls excel文件时出错

时间:2010-09-15 08:35:37

标签: c# .net asp.net excel ms-office

我创建了一个程序,我从数据库中读取记录集,然后将其保存在数据网格中。从这里开始,我让用户将文件下载为excel文件。

现在,用户对文件进行了更改,然后再次上传,并从此处读取上传的.xls文件并在数据库中进行必要的更改。

问题是每当用户上传更新的excel文件时,我都无法访问它并收到错误。

  

外部表格不符合预期   格式

我让用户将文件下载为

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();
                }
            }

用户在进行更改后上传文件,我将其视为

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");

请帮助。感谢。

2 个答案:

答案 0 :(得分:0)

OLEDB可能无法读取您生成的XLS文件版本吗? Excel 8是Excel 97,您可能会生成Excel 2007 .xlsx格式。

答案 1 :(得分:0)

是的,我同意布莱恩!您可能正在生成要阅读的其他.xlsx格式。

试试这个:http://www.aspdotnet-suresh.com/2010/09/import-data-from-excel-to-sql-database.html

相关问题