【问题标题】:Export to Excel function working in localhost but not in published website导出到 Excel 功能在 localhost 但不在已发布网站中工作
【发布时间】:2016-01-17 12:19:54
【问题描述】:

我有这段代码可以将我的 GridViews 导出到 Excel,它可以在 localhost 中运行,但在部署后它不起作用。单击导出按钮时收到的错误是运行时错误。

protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();

            // creating new WorkBook within Excel application
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            String DATA1 = "DATA1";
            String DATA2 = "DATA2";
            ExportToExcel(app, workbook, DATA_1, DATA1);
            workbook.Worksheets["Sheet1"].Delete();
            workbook.Worksheets["Sheet2"].Delete();
            workbook.Worksheets["Sheet3"].Delete();
            ExportToExcel(app, workbook, DATA_2, DATA2);
            string FolderPath = ServerName + DirectoryLocation + DirectoryFolder + ExportsFolder;
            var filename = @"EXCEL_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";
            workbook.SaveAs(FolderPath + filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            workbook.Close();
            app.Quit();
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
            Response.TransmitFile(FolderPath + filename);
            Response.Flush();
            Response.End();
        }

        public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName)
        {
            // see the excel sheet behind the program
            app.Visible = false;

            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.Add();

            // changing the name of active sheet
            worksheet.Name = SheetName;

            // storing header part in Excel
            for (int i = 1; i < gridview.Columns.Count + 1; i++)
            {
                worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
            }


            // storing Each row and column value to excel sheet
            for (int i = 0; i < gridview.Rows.Count - 1; i++)
            {
                for (int j = 0; j < gridview.Columns.Count; j++)
                {
                    worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
                }
            }

        }

【问题讨论】:

  • 愚蠢的问题,但是office是否安装在服务器上?
  • @MyDaftQuestions 没有。但是不能生成文件类型吗?×
  • 服务器不安装Office,可以按照Greco推荐的方式导出csv。如果您需要格式化、公式支持等,那么您将不得不使用第三方库。 .NET 有很多可用的,也是开源的。

标签: asp.net excel c#-4.0 gridview


【解决方案1】:

我使用 EPPLUS 解决了我的问题,EPPlus 是一个 .net 库,它使用 Open Office Xml 格式 (xlsx) 读写 Excel 2007/2010 文件。它不需要在服务器机器上安装 excel。谢谢。

以下代码仅供参考:

protected void ExportToExcel_Click(object sender, EventArgs e)
    {
        var products = GetProducts();
        GridView1.DataSource = products;
        GridView1.DataBind();
        ExcelPackage excel = new ExcelPackage();
        var workSheet = excel.Workbook.Worksheets.Add("Products");
        var totalCols = GridView1.Rows[0].Cells.Count;
        var totalRows = GridView1.Rows.Count;
        var headerRow = GridView1.HeaderRow;
        for (var i = 1; i <= totalCols; i++ )
        {
            workSheet.Cells[1, i].Value = headerRow.Cells[i - 1].Text;
        }
        for (var j = 1; j <= totalRows; j++ )
        {
            for (var i = 1; i <= totalCols; i++)
            {
                var product = products.ElementAt(j-1);
                workSheet.Cells[j + 1, i].Value = product.GetType().GetProperty(headerRow.Cells[i - 1].Text).GetValue(product, null);
            }
        }
        using (var memoryStream = new MemoryStream())
        {
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=products.xlsx");
            excel.SaveAs(memoryStream);
            memoryStream.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();
        }
    }

【讨论】:

    【解决方案2】:

    “Microsoft.Office.Interop.Excel”表示必须安装 Microsoft Office 运行时才能使此代码正常工作。

    避免使用 Microsoft.Office.Interop.Excel 导出数据,因为它需要在服务器上安装应用程序,可扩展性差,并且违反 MS Office 许可条件。

    我建议其他方法,例如 text-csv 导出,这将在服务器上满足更好的性能。

    protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
    {
     ...
     StringBuilder sb = new StringBuilder();
    
     // storing header part in Excel
     for (int i = 1; i < gridview.Columns.Count + 1; i++)
     {
         sb.Append (gridview.Columns[i - 1].HeaderText);
         stringBuilder.Append(",");
     }
    
     sb.Append(Environment.NewLine);
    
     // storing Each row and column value to excel sheet
     for (int i = 0; i < gridview.Rows.Count - 1; i++)
     {
         for (int j = 0; j < gridview.Columns.Count; j++)
         {
           sb.Append (gridview.Rows[i].Cells[j].Text.ToString());
           stringBuilder.Append(",");
         }
         sb.Append(Environment.NewLine);
      }
    
      WriteToCSV(sb.ToString(); 
    }
    
    public static void WriteToCSV(string text, string fileName)
      {
          string attachment = "attachment; filename="+fileName+DateTime.Now.ToString("yy-MM-dd")+".csv";
          HttpContext.Current.Response.Clear();
          HttpContext.Current.Response.ClearHeaders();
          HttpContext.Current.Response.ClearContent();
          HttpContext.Current.Response.AddHeader("content-disposition", attachment);
          HttpContext.Current.Response.ContentType = "text/csv;charset=utf8";
          HttpContext.Current.Response.AddHeader("Pragma", "public");
    
          HttpContext.Current.Response.Write('\uFEFF'); //this is BOM
          HttpContext.Current.Response.Write(text);
          HttpContext.Current.Response.End();
      }
    

    【讨论】:

    • 嗨,我可以和你确认一下,如果我使用 OpenXML SDK,Excel 仍然需要安装在服务器端才能正常工作,我说得对吗?
    • 不! OpenXML 非常适合服务器应用程序,无需安装即可工作。
    【解决方案3】:

    失败的原因是您没有安装 Excel。这里还有其他选项(例如转换为 CSV 文件),但如果您想按原样使用您的代码,最简单的方法可能是在服务器上安装 Excel!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-18
      • 2014-10-07
      • 1970-01-01
      • 2021-11-14
      • 2012-04-30
      • 1970-01-01
      • 2014-10-09
      相关资源
      最近更新 更多