2015-10-23 106 views
0

我有一個ASP.NET應用程序,它可以幫助用戶創建一個帶有特定數據的Gridview。一旦生成此表我希望用戶按下一個按鈕,並能夠保存表爲Excel document.There兩種不同的方法,我知道的:使用ASP.NET生成Excel文檔網站

  1. 使用的HtmlTextWriter與ContentType的「應用程序/越南盾。 ms-excel「將該文件作爲HttpResponse發送。我使用GridView1.RenderControl(htmlTextWriter)來呈現gridview。這幾乎可以工作,但當文件打開時,excel文件總是顯示警告,因爲內容與擴展名不匹配。我嘗試了各種內容類型無濟於事。這是有道理的,因爲我正在使用HtmlWriter。這似乎也不是一個好習慣。

  2. 我試過的第二件事是使用Office自動生成Excel文件。但是對於要生成的文件,我需要將其保存到磁盤然後再次讀取。從我讀過的內容來看,這是唯一的辦法,因爲Excel對象一旦保存就只會變成真正的Excel文件。我發現Excel類中的.saveas方法會因寫入權限而引發異常,即使我試圖保存在App_Data文件夾中。所以,我做了一些研究,發現顯然辦公自動化是鼓勵使用Web服務:https://support.microsoft.com/en-us/kb/257757

微軟目前並不提倡,不支持, 自動化的Microsoft Office應用程序從任何無人值守, 非交互式客戶端應用程序或組件(包括ASP, ASP.NET,DCOM和NT服務),因爲Office在此環境中運行Office時可能會出現不穩定的 行爲和/或死鎖。

肯定必須有一種保存方式讓網站生成一個Excel文件並提供給用戶!我無法想象這個問題沒有得到解決,也沒有人關心這個問題,但我找不到任何好的解決方案。

回答

0

創建一個Excel文件的最簡單的(和最好)的方法是使用epplus

Epplus sample for webapplication

  using (ExcelPackage pck = new ExcelPackage()) 
      { 
       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.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
       Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx"); 
       Response.BinaryWrite(pck.GetAsByteArray()); 
} 
+0

這看起來像一個有用的工具,但我扶正爲我公司與該Web應用程序我認爲GNU許可證不會解決問題。從這裏和其他線索我缺乏答案我GOOGLE了,我覺得沒有第三方工具沒有好辦法!?那真的是這樣嗎? – user2696330

+0

epplus是最好的辦法,如果你想要一個產品,那麼我可以推薦軟工匠excel /辦公室作家,但它是相當昂貴的 – Thorarins

+0

沒有第三方,是的好epplus是用c#和.net編寫的,所以看看在源代碼中,做同樣的事情你自己... – Thorarins