如何将数据从excel表插入到asp.net中的datatable?

时间:2012-08-30 05:53:39

标签: c# asp.net excel import datatable

我想将excel表中的数据插入到datatable中,这很正常。但我不知道为什么我现在收到以下错误

“Microsoft Jet数据库引擎找不到对象'Sheet1'。请确保该对象存在,并且您正确拼写其名称和路径名。”

我的代码是检索数据

 if (fupExcel.HasFile)
        {
            // Get the name of the Excel spreadsheet to upload.
            string strFileName = Server.HtmlEncode(fupExcel.FileName);
            strAct = "New Schedule is uploaded, File name:" + strFileName;

            // Get the extension of the Excel spreadsheet.
            string strExtension = Path.GetExtension(strFileName);

            // Validate the file extension.
            if (strExtension != ".xls" && strExtension != ".xlsx")
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ntexl", "alert('Please select a Excel spreadsheet to import!');", true);
                return;
            }

            // Generate the file name to save.
            //string uploadFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + strExtension;
            uploadFileName = CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time").ToString("yyyyMMddHHmmss") + strExtension;

            // Save the Excel spreadsheet on server.
            fupExcel.UploadFile(uploadPath, uploadFileName);

            ClsScheduleFileNew objCLSSchedule = new ClsScheduleFileNew();
            ClsScheduleFileNewProp objUserFile = new ClsScheduleFileNewProp();

            objUserFile.FileName = strFileName;
            objUserFile.FilePath = uploadFileName;
            objUserFile.CreatedDate = CCMMUtility.GetCurrentDateTimeByTimeZone("US Mountain Standard Time"); //DateTime.Now;
            ScheduleFileId = objCLSSchedule.InsertFileInfo(objUserFile);
            hdfScheduleFileId.Value = ScheduleFileId.ToString();
            if (ScheduleFileId != 0)
            {
                //ViewState["nw_Upload"] = ScheduleFileId;
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "err", "alert('Some error occured while exporting the file.');", true);
                return;
            }
            // Generate the connection string for Excel file.
            strExcelConn = uploadPath;

            // There is no column name In a Excel spreadsheet. 
            // So we specify "HDR=YES" in the connection string to use 
            // the values in the first row as column names. 
            if (strExtension == ".xls")
            {
                // Excel 97-2003
                strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strExcelConn + uploadFileName + ";Extended Properties='Excel 8.0;HDR=YES;'";
            }
            else
            {
                // Excel 2007
                strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelConn + uploadFileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES;'";
            }
            hdfStrExcelConn.Value = strExcelConn;
            try
            {
                ImportData(uploadFileName, uploadPath, strExcelConn, ScheduleFileId);
            }
            catch (Exception)
            {
                //Delete file over here and database entry over here.
                string path = uploadPath + uploadFileName;
                CCMMUtility.DeleteFilefromLocation(path);
                objCLSSchedule.DeleteScheduleFile(ScheduleFileId);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ntmtch", "alert('Some column values are not matched.');", true);
                return;
            }
        }

Improt函数的代码是

 DataTable dt = new DataTable();
        DataRow row;
        DataTable dtExcel = CreateDataTable();

        using (OleDbConnection conn = new OleDbConnection(strConn))
        {
            OleDbDataAdapter da = new OleDbDataAdapter("select * from [Sheet1]", conn);
            da.Fill(dt);// here i am getting that error

            // Create new datatable having non empty rows
            DataTable filteredDataTable = (dt.Rows.Cast<DataRow>().Where(t => t.ItemArray.Any(field => !(field is DBNull)))).CopyToDataTable<DataRow>();

            // Fill the DataTable with data from the Excel spreadsheet.
            if (filteredDataTable.Rows.Count > 0)
            {
// my code hete to fill datatable }

2 个答案:

答案 0 :(得分:2)

尝试使用:

"select * from [Sheet1$]"

我认为$是必需的。

答案 1 :(得分:0)

编写我尝试的解决方案。

将Excel工作表存储为逗号分隔文件,并将其另存为.txt

然后使用以下逻辑将其导入数据表。

 using (StreamReader sr = new StreamReader("C://File.txt"))
        {
            String line;
            int index = -1;
            while ((line = sr.ReadLine()) != null)
            {
                index++;
                iIndexofComma = line.IndexOf(@",");
                iLength = line.Length;
                dt.Rows.Add();
                dt.Rows[index]["col1"] = line.Substring(0, iIndexofComma);
                dt.Rows[index]["col2"] = line.Substring(iIndexofComma + 1, iLength - iIndexofComma - 1);
                dtMapping.AcceptChanges();
            }
        }

希望有所帮助。