2011-12-20 115 views

回答

1

Take a look at EPPlus。这是一个谷歌代码托管项目,可以“在服务器上创建高级Excel 2007/2010电子表格.EPPlus是一个.net库,它使用Open Office Xml格式(xlsx)读取和写入Excel 2007/2010文件。”

将文件导入到我的项目中后,我花了一些时间才将它实际运行,所以我会给你一些正在工作的示例代码。代码可能并不完全是你想要用你的文件做的,但它会给你一个很好的模板。

在页面生命周期方面:代码是.ashx处理页面上,所以我打开domain.com/toexcel.ashx在浏览器中,并下载文件。

这个库对我来说工作得非常好,文件输出似乎是完全有效/兼容的Excel文件。

顺便说一句,我不是下属,只是一个大风扇:)

<%@ WebHandler Language="C#" Class="excel" %> 

using System; 
using System.Web; 
using OfficeOpenXml; 
using OfficeOpenXml.Drawing; 
using OfficeOpenXml.Style; 
using System.Drawing; 
using System.Data; 


public class excel : IHttpHandler { 

    public void ProcessRequest (HttpContext context) { 
     using (ExcelPackage pck = new ExcelPackage()) 
     { 
      int id = int.Parse(context.Request.QueryString["id"]); 
      DateTime now = DateTime.Now; 

      //get and format datatable 
      Project proj = new Project(id); 
      DataTable items = proj.getItemsDataTable(); 

      items = PmFunctions.prettyDates(items); 
      items = PmFunctions.prettyMoney(items); 

      //new worksheet 
      ExcelWorksheet ws = pck.Workbook.Worksheets.Add(proj.getTitle()); 

      //load data 
      ws.Cells["A1"].Value = proj.getTitle(); 
      ws.Cells["A1"].Style.Font.Size = 20; 

      ws.Cells["A2"].Value = "Report Date:"; 
      ws.Cells["C2"].Value = now.ToShortDateString(); 

      ws.Cells["A4"].Value = "Estimate Total:"; 
      ws.Cells["C4"].Value = String.Format("{0:C}", proj.getProjectEstimate()); 

      ws.Cells["A5"].Value = "Actual Total:"; 
      ws.Cells["C5"].Value = String.Format("{0:C}", proj.getProjectTotal()); 

      ws.Cells["A7"].LoadFromDataTable(items, true); 

      //Stylings 
      using (ExcelRange rng = ws.Cells["A7:J7"]) 
      { 
       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); 
      } 



      //Write to the response 
      context.Response.Clear(); 
      context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
      context.Response.AddHeader("content-disposition", "attachment; filename=" + proj.getTitle() + " Report - " + now.ToShortDateString() + ".xlsx"); 
      context.Response.BinaryWrite(pck.GetAsByteArray()); 
     } 
    } 

    public bool IsReusable { 
     get { 
      return false; 
     } 
    } 
} 
相关问题