c# - 将数据导出到 excel 文件 2003、2007 及更高版本

标签 c# asp.net excel

我正在使用这些连接字符串,具体取决于文件的扩展名:

对于 2003 年:Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties='Excel 8.0;

对于 2007 年:Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;

这里是获取连接。

string con_excel = "";

        switch (Extension.ToLower())
        {
            case ".xls":
                con_excel = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                break;

            case ".xlsx":
                con_excel = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;
        }
        con_excel = con_excel.Replace("filename", filePath);

下面是生成excel文件的代码。

        Excel.Application oXL;
        Excel._Workbook oWB;
        Excel._Worksheet oSheet;

        oXL = new Excel.Application();
        oXL.Visible = false;

        oXL.SheetsInNewWorkbook = 1;
        oWB = (Excel._Workbook)(oXL.Workbooks.Add());
        oSheet = (Excel._Worksheet)oWB.ActiveSheet;

        try
        {
            string[] colNames = new string[dataTable.Columns.Count];

            int col = 0;

            foreach (DataColumn dc in dataTable.Columns)
                colNames[col++] = dc.ColumnName;

            char lastColumn = (char)(65 + dataTable.Columns.Count - 1);

            oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
            oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
            oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;

            DataRow[] dr = dataTable.Select();

            string[,] rowData = new string[dr.Count<DataRow>(), dataTable.Columns.Count + 1];

            int rowCnt = 0;
            foreach (DataRow row in dr)
            {
                for (col = 0; col < dataTable.Columns.Count; col++)
                {
                    rowData[rowCnt, col] = row[col].ToString();
                }
                rowCnt++;
            }
            rowCnt++;
            oSheet.get_Range("A2", lastColumn + rowCnt.ToString()).Value = rowData;

            oXL.Visible = false;
            oXL.UserControl = true;

            String sNewFolderName = "Report_" + intReportId;
            filename = Server.MapPath("Your Report\\" + sNewFolderName + DateTime.Now.ToString("dd-MM-yyyy_hh-mm-ss") + Extension);
            oSheet.SaveAs(filename);

            System.Runtime.InteropServices.Marshal.ReleaseComObject(oWB);

            oXL.Quit();

            Marshal.ReleaseComObject(oSheet);
            Marshal.ReleaseComObject(oWB);
            Marshal.ReleaseComObject(oXL);

            oSheet = null;
            oWB = null;
            oXL = null;
            GC.GetTotalMemory(false);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.GetTotalMemory(true);

            //The excel is created and opened for insert value. We most close this excel using this system        
            Process[] localByName = Process.GetProcessesByName("EXCEL");
            foreach (Process process in localByName)
            {
                process.Kill();
            }

2007文件格式可以。

我尝试上传2003(.xls) excel 文件,然后也生成2003(.xls) 格式。但是,当我打开该文件时,出现以下错误。

您尝试打开的文件“FileName.xls”的格式与指定的文件扩展名不同。在打开文件之前,确认文件未损坏且来源可靠。您现在要打开文件吗?

这是因为连接字符串吗?

最佳答案

试试这个代码上传Excel 2003和2007文件

  if (filenam.ToString() == ".xls")
    { constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathnam + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\""; }
    else if (filenam.ToString() == ".xlsx")
    { constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathnam + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\""; }
    else { Response.Write("<script>alert('Load Excel file Only')</script>"); }
    string Qry = "SELECT [Customer], [Project], [Contact], [Designation], [Phone], [EmailID],[Region] FROM [Sheet1$]";
    OleDbConnection conn = new OleDbConnection(constr);
    if (conn.State == ConnectionState.Closed)
    {
    conn.Open();
    OleDbCommand cmd = new OleDbCommand(Qry, conn);
    OleDbDataAdapter da = new OleDbDataAdapter();
    da.SelectCommand = cmd;
    DataTable dt = new DataTable();
    da.Fill(dt);
    if (dt != null && dt.Rows.Count > 0)
    {
    gv_upload.DataSource = dt;
    gv_upload.DataBind();
    }
    da.Dispose(); conn.Close(); conn.Dispose();

关于c# - 将数据导出到 excel 文件 2003、2007 及更高版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20208328/

相关文章:

c# - 混淆 Xamarin 应用程序

C# lambda 内容在被调用之前不会发生,对吗?另外,代码清理

c# - 哈希整数数组

jquery - 如何使用 AJAX 将字符串传递给 Controller

Python循环等效Excel偏移等效?

c# - LinkedIn - 是否可以在我的应用程序的用户组中发帖?

asp.net - Entity Framework ,将列更改为只读

c# - 为什么 datetime 在存储时不记录时间?

excel - 如何保存工作簿并处理 TITUS(或任何其他文档分类插件)弹出窗口?

c# - 如何使用 EPPlus 库为 Excel 创建多样式单元格