0

我需要将 Excel 文件中的数据加载到 SQL Server 数据库中。Excel 文件是通过将数据从 Web 应用程序下载到数据集中来创建的。从 SQL Server 数据库中的表中提取数据以生成 Excel。当我尝试将同一个 Excel 文件上传到同一个表中时,它会出错。

 HResult=-2147467259 Message=Could not find installable ISAM.
 Source=Microsoft JET Database Engine ErrorCode=-2147467259

'Report.xls' 的文件格式和扩展名与文件不匹配不能损坏或不安全。除非你相信它的来源,否则不要打开它。你还是要打开它吗?

这是将数据保存到数据库中的代码

      private void SaveFileToDatabase(string filePath)
      {
          String fileExtension = Path.GetExtension(filePath);
          String excelConnString = string.Empty;

          //Create connection string to Excel work book
          if (fileExtension == ".xls")
          {
              excelConnString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1""", filePath);
              //String excelConnString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties="Excel 8.0;HDR=Yes;IMEX=1""", filePath);
          }
          else
          {
              excelConnString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0""", filePath);
          }

          //Connection to Excel work book 
          using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
          {
              //OleDbCommand to fetch data from Excel 
              using (OleDbCommand cmd = new OleDbCommand("Select * from [working$]", excelConnection))
              {
                  excelConnection.Open();
                  using (OleDbDataReader dReader = cmd.ExecuteReader())
                  {
                      using (SqlBulkCopy sqlBulk = new SqlBulkCopy(connect))
                      {
                          DBUtilities.RunSQLCommand("truncate table dbo.[DatabaseTable]");

                          //Destination table in db
                          sqlBulk.DestinationTableName = " DatabaseTable ";
                          sqlBulk.WriteToServer(dReader);
                      }
                  }
          }
      }
      }

从表中的数据创建 Excel 文件的代码

    private void ExportDataToExcel(String sprocCommand, String workBookName)
    {
        try
        {
            string attachment = "attachment; filename=report.xls";

            Response.Clear();
            Response.Buffer = true;
            Response.Charset = string.Empty;
            Response.AddHeader("cache-control", "private");
            Response.AddHeader("Content-disposition", attachment);
            //Response.AddHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            Response.ContentType = "application/vnd.xls";
            EnableViewState = false;

            DataTable dt = DBUtilities.GetData();
            DataView dv = dt.DefaultView;

            dt = null;
            dt = dv.ToTable();

            Response.Write(SendExcelXMLFormat(dt, workBookName));

            Response.End();
        }
        catch (Exception Ex)
        {
            ////TOOD   
        }
    }

    private string SendExcelXMLFormat(DataTable dTable, string WorkSheetName)
    {
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("<?xml version=\"1.0\"?> ");
        sb.AppendLine("<?mso-application progid=\"Excel.Sheet\"?> ");
        sb.AppendLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
        sb.AppendLine("xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
        sb.AppendLine("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
        sb.AppendLine("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
        sb.AppendLine("xmlns:html=\"http://www.w3.org/TR/REC-html40\"> ");
        sb.AppendLine("<Styles> ");
        sb.AppendLine("<Style ss:ID=\"s41\" ss:Name=\"60% - Accent1\"> ");
        sb.AppendLine("<Font ss:FontName=\"Calibri\" x:Family=\"Swiss\" ss:Size=\"11\" ss:Color=\"#FFFFFF\"/> ");
        sb.AppendLine("<Interior ss:Color=\"#95B3D7\" ss:Pattern=\"Solid\"/> ");
        sb.AppendLine("</Style> ");
        sb.AppendLine("</Styles> ");
        sb.AppendLine("<Worksheet ss:Name=\"" + WorkSheetName+"\"> ");
        sb.AppendLine("<Table>");

        // Header Row
        sb.AppendLine("<Row ss:AutoFitHeight=\"0\"> ");
        foreach (DataColumn dc in dTable.Columns)
        {
            sb.AppendLine("<Cell ss:StyleID=\"s41\"><Data ss:Type=\"String\">" + dc.ColumnName + "</Data></Cell> ");
        }
        sb.AppendLine("</Row> ");

        // Data Rows
        foreach (DataRow row in dTable.Rows)
        {
            sb.AppendLine("<Row ss:AutoFitHeight=\"0\"> ");
            for (int i = 0; i < dTable.Columns.Count; i++)
            {
                sb.AppendLine("<Cell><Data ss:Type=\"String\">" + Server.HtmlEncode(row[i].ToString()) + "</Data></Cell> ");
            }
            sb.AppendLine("</Row> ");
        }

        sb.AppendLine("</Table> ");
        sb.AppendLine("</Worksheet> ");
        sb.AppendLine("</Workbook> ");

        return sb.ToString();
    }
4

1 回答 1

1

如果要将数据从 Excel 存储到 SQL Server,请参考此链接

http://www.codeproject.com/Tips/593181/Load-GridView-from-Excel

在这里,我从 excel 加载了 gridview,并使用 SQLBulkCopy() 将 excel 的内容复制到 SQL Server。注意:您还可以从 gridview 获取单个行并插入到数据库中。

看看它可能会有所帮助。

于 2013-11-12T12:25:49.633 回答