在asp.net中创建Excel工作簿

时间:2012-04-07 20:26:12

标签: c# asp.net vsto ms-office

我需要在点击按钮时为用户生成一个excel文件。我之前使用的是Netoffice,它适用于桌面应用程序。 但现在我想用asp.net应用程序做同样的事情。这样我的服务器代码就无法访问客户端的excel副本。我应该采取什么方法?

5 个答案:

答案 0 :(得分:8)

使用EPPlus。它允许您在服务器上创建Excel电子表格。我用过它并且效果很好。它支持高级功能。

using (ExcelPackage pck = new ExcelPackage())
{
    //Create the worksheet
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");

    //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
    ws.Cells["A1"].LoadFromDataTable(tbl, true);

    //Format the header for column 1-3
    using (ExcelRange rng = ws.Cells["A1:C1"])
    {
        rng.Style.Font.Bold = true;
        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;

        //Set Pattern for the background to Solid
        rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));

        //Set color to dark blue
        rng.Style.Font.Color.SetColor(Color.White);
    }

    //Example how to Format Column 1 as numeric 
    using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
    {
        col.Style.Numberformat.Format = "#,##0.00";
        col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
    }

    //Write it back to the client
    Response.Clear();
    Response.AddHeader("content-disposition", "attachment;  filename=file.xlsx");
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";                    
    Response.BinaryWrite(pck.GetAsByteArray());
    Response.End();
}

答案 1 :(得分:3)

最灵活,最有可能完成你所需要的是做一些工作,但它是免费的 - 而且确实有效。使用工具包查看现有文档,了解如何创建所需的功能。

Open XML 2.0 SDK

答案 2 :(得分:0)

您可以尝试简单的HTML表格(包括html,head和body标签)。 只需使用XLS扩展名保存即可。


enter image description here

答案 3 :(得分:0)

Netoffice要求MS Office执行机器。你的服务器有吗?

答案 4 :(得分:0)

您可以使用DataGrid动态创建Excel文件。它不需要Excel。

public static void ExportDataSetToExcel(DataSet ds, string filename)
{
    HttpResponse response = HttpContext.Current.Response;

    // first let's clean up the response.object
    response.Clear();
    response.Charset = "";

    // set the response mime type for excel
    response.ContentType = "application/vnd.ms-excel";
    response.AddHeader(
        "Content-Disposition",
        "attachment;filename=\"" + filename + "\""
    );

   // create a string writer
   using (StringWriter sw = new StringWriter())
   {
       using (HtmlTextWriter htw = new HtmlTextWriter(sw))
       {
            // instantiate a datagrid
            DataGrid dg = new DataGrid();
            dg.DataSource = ds.Tables[0];
            dg.DataBind();
            dg.RenderControl(htw);
            response.Write(sw.ToString());
            dg.Dispose();
            ds.Dispose();
            response.End();
       }
    }
}