尝试从Excel文件填充Datatable时出错

时间:2014-12-19 18:15:20

标签: .net excel datatable oledb

我正在尝试将excel文件中的数据转换为数据表。我的代码如下,我的错误是," IErrorInfo.GetDescription因E_FAIL(0x80004005)而失败。"并且此错误发生在该行," dbAdapter.Fill(dt);"

    protected void uploadFile()
    {
        try
        {
            if (ctlFileUpload.HasFile)
            {
                string strFileType = System.IO.Path.GetExtension(ctlFileUpload.FileName).ToString().ToLower();
                if (strFileType == ".xls" || strFileType == ".xlsx")
                {
                    DataTable dt = new DataTable();
                    string strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text\"", ctlFileUpload);

                    using (OleDbConnection dbConnection = new OleDbConnection(strConn))
                    {
                        using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", dbConnection)) //rename sheet if required!
                            dbAdapter.Fill(dt);
                        int rows = dt.Rows.Count;
                    }

                }
                else { throw new Exception("Excel File Only"); }
            }
        }
        catch (Exception ex)
        {

            if (ex.Message == "Incorrect Format")
            {
                lblStatusMessage.Text = "Excel is in an incorrect format, please use the template provided.";

            }
            else if (ex.Message == "Excel File Only")
            {
                lblStatusMessage.Text = "Only Excel files are allowed, please use the template provided.";
                return;
            }
            else
            {
                lblStatusMessage.Text = ex.Message;
                return;
            }
        }

    }

我上传的文件中没有任何空格,并且格式为.xlsx。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为您需要在连接字符串中使用之前保存该文件 连接字符串也应该使用FileName属性而不是整个FileUpload控件

所以例如

....
if (ctlFileUpload.HasFile)
{
    string strFileType = System.IO.Path.GetExtension(ctlFileUpload.FileName).ToLower();
    if (strFileType == ".xls" || strFileType == ".xlsx")
    {
        string fileName = "/APP_DATA/" + ctlFileUpload.FileName;
        ctlFileUpload.SaveAs(fileName);

        string strConn = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;
                         Data Source={0};Extended Properties=\"Excel 12.0 Xml;
                         HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text\"", 
                         fileName);
    .....