导出到Excel功能在localhost中工作但不在已发布的网站中

时间:2015-10-19 08:12:12

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

我有这个代码将我的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();
                }
            }

        }

3 个答案:

答案 0 :(得分: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();
        }
    }

答案 1 :(得分:0)

<强>&#39;的Microsoft.Office.Interop.Excel&#39;表示必须安装Microsoft Office Runtime才能使此代码正常工作。

避免使用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();
  }

答案 2 :(得分:0)

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