2011-12-20 113 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; 
     } 
    } 
} 
相關問題