Web C# 導出Excel 方法總結


方法1:微軟推薦服務器需安裝Excel型

依賴:

軟件:Office Excel 2007-2013

引用:Microsoft Office 14.0 Object Library

1.1 數據准備

 1 //Excel文件名稱
 2     string ExcelName = System.DateTime.Now.ToString("yyMMdd") + "退款結算單.xlsx";
 3 
 4     /// <summary>
 5     /// 批量退款
 6     /// </summary>
 7     /// <param name="sender"></param>
 8     /// <param name="e"></param>
 9     protected void Button1_Click(object sender, EventArgs e)
10     {
11         DataSet ds = new DataSet();
12 
13         DataTable dt1 = new DataTable();
14         dt1.Columns.Add("批次號");
15         dt1.Columns.Add("總金額(元)");
16         dt1.Columns.Add("總筆數");
17 
18         DataRow row1 = dt1.NewRow();
19 
20         row1 = dt1.NewRow();
21         row1["批次號"] = "20150425001";
22         row1["總金額(元)"] = "0.03";
23         row1["總筆數"] = "1";
24         dt1.Rows.Add(row1);
25 
26         ds.Tables.Add(dt1);
27 
28         DataTable dt2 = new DataTable();
29         dt2.Columns.Add("商戶訂單號");
30         dt2.Columns.Add("支付寶交易號");
31         dt2.Columns.Add("退款金額");
32         dt2.Columns.Add("退款備注");
33 
34         DataRow row2 = dt2.NewRow();
35 
36         row2 = dt2.NewRow();
37         row2["商戶訂單號"] = "D150418092109-40";
38         row2["支付寶交易號"] = "2015041800001000770049196543";
39         row2["退款金額"] = "0.02";
40         row2["退款備注"] = "導入excel測試";
41         dt2.Rows.Add(row2);
42 
43         ds.Tables.Add(dt2);
44 
45 
46         doExport(ds, Server.MapPath(ExcelName));
47     }

1.2 數據寫入

 1  private Microsoft.Office.Interop.Excel.Application _Excel = null;
 2 
 3     /// <summary>
 4     /// 將 DataSet 數據寫入 _Excel
 5     /// </summary>
 6     /// <param name="ds"></param>
 7     /// <param name="strExcelFileName"></param>
 8     private void doExport(DataSet ds, string strExcelFileName)
 9     {
10         int rowIndex = 1;//當前行數
11         int colIndex = 0;//當前列數
12 
13 
14         _Excel = new Microsoft.Office.Interop.Excel.Application();
15         _Excel.Application.Workbooks.Add(true);
16 
17 
18         for (int i = 0; i < ds.Tables.Count; i++)
19         {
20             DataTable table = ds.Tables[i];
21             colIndex = 0;//列初始化
22             // 列標題
23             foreach (DataColumn col in table.Columns)
24             {
25                 colIndex++;
26                 _Excel.Cells[rowIndex, colIndex] = col.ColumnName;
27             }
28 
29             // 內容
30             foreach (DataRow row in table.Rows)
31             {
32                 rowIndex++;
33                 colIndex = 0;
34                 foreach (DataColumn col in table.Columns)
35                 {
36                     colIndex++;
37                     _Excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
38                 }
39             }
40 
41             rowIndex++;//行+1 防止table又多個情況
42         }
43 
44         _Excel.Visible = false;
45         // 保存文件
46         SaveToDisk(strExcelFileName);
47 
48         _Excel.Quit();
49         _Excel = null;
50     }

1.3 數據導出

 1   /// <summary>
 2     /// 導出方法
 3     /// </summary>
 4     /// <param name="path">路徑</param>
 5     private void SaveToDisk(string path)
 6     {
 7         if (!string.IsNullOrEmpty(path))
 8         {
 9             System.IO.FileInfo info = new FileInfo(path);
10             if (!info.Exists)
11             {
12                 _Excel.ActiveWorkbook.SaveCopyAs(path);
13 
14                 /*
15                 微軟為Response對象提供了一個新的方法TransmitFile來解決使用Response.BinaryWrite
16                 下載超過400mb的文件時導致Aspnet_wp.exe進程回收而無法成功下載的問題。
17                 代碼如下:
18                */
19                 Response.ContentType = "text/xml";
20                 Response.AddHeader("Content-Disposition", "attachment;filename=" + ExcelName);
21                 string filename = Server.MapPath(ExcelName);
22                 Response.TransmitFile(filename);
23             }
24             else
25             {
26                 info.Delete();
27                 _Excel.DisplayAlerts = false;
28                 _Excel.AlertBeforeOverwriting = false;
29                 _Excel.ActiveWorkbook.SaveCopyAs(path);
30             }
31         }
32     }

 

方法2:第三方組件NPOI(2.0版本后受到微軟支持)

依賴:

NPOI.dll

NPOI.OOXML.dll

NPOI.OpenXml4Net.dll

NPOI.OpenXmlFormats.dll

NPOI下載地址 - http://npoi.codeplex.com/releases

2.1 簡單例子:

 1 using NPOI.XSSF.UserModel;
 2 using NPOI.SS.UserModel;
 3 
 4 //創建全新的Workbook
 5 IWorkbook workbook = new XSSFWorkbook();
 6 
 7 //創建Sheet
 8 workbook.CreateSheet("Sheet1");
 9 
10 //寫入一個簡單日期 並設置格式
11 ISheet sheet = hssfworkbook.CreateSheet("Sheet1");
12 ICell cell = sheet.CreateRow(0).CreateCell(0);
13 cell.SetCellValue(new DateTime(2008,5,5));
14 //set date format
15 ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
16 IDataFormat format = hssfworkbook.CreateDataFormat();
17 cellStyle.DataFormat = format.GetFormat("yyyy年m月d日");
18 cell.CellStyle=cellStyle;
19 
20 //保存Workbook
21 FileStream sw = File.Create("test.xlsx");
22 workbook.Write(sw);
23 sw.Close();

 

這樣就好了。

 

2.2 復雜例子(包含下載功能)

     /// <summary>
     /// 導出Excel
     /// </summary>
     /// <param name="ExcelName">文件名稱</param>
     public void NPOIExcel(DataSet ds, string ExcelName)
     {
         int row_index = 0;
         //創建全新的Workbook
         IWorkbook workbook = new XSSFWorkbook();
 
 
         //創建Sheet
         workbook.CreateSheet("Sheet1");

         //根據Sheet名字獲得Sheet對象
         ISheet sheet = workbook.GetSheet("Sheet1");
         IRow row;
 
         row = sheet.CreateRow(row_index);
         for (int i = 0; i < ds.Tables.Count; i++)
         {
             //寫入標題
             for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
             {
                 row.CreateCell(j).SetCellValue(ds.Tables[i].Columns[j].Caption.ToString());
 
             }
             row = sheet.CreateRow(++row_index);

             //寫入數據
             foreach (DataRow r in ds.Tables[i].Select())
             {
                 for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                 {
                     row.CreateCell(j).SetCellValue(r[j].ToString());
                 }
 
                 row = sheet.CreateRow(++row_index);
             }
 
 
         }
 
         //保存Workbook方式一: 以文件形式保存到服務器中(每次導出都會生成一個文件,慎重使用)
         FileStream sw = File.Create(Server.MapPath("file/" +ExcelName));
         workbook.Write(sw);
         sw.Close();

         //保存Workbook方式二: 保存到內存流中
         var stream = new MemoryStream();
         workbook.Write(stream);

 
         //文件下載
         Response.Clear();
         Response.Charset = "utf-8";
         Response.Buffer = true;
         this.EnableViewState = false;
         Response.ContentEncoding = System.Text.Encoding.UTF8;
 
         Response.ContentType = "application/vnd.ms-excel";
         Response.AddHeader("Content-Disposition", "attachment;filename="+ExcelName);

         string filename =Server.MapPath("file/" + ExcelName);//通過服務器文件下載
         Response.WriteFile(filename);
         Response.BinaryWrite(StreamToBytes(stream));//通過內存流下載,StreamToBytes為Stream轉byte[] 方法 可查看我其他隨筆有
         Response.Flush();   Response.Close(); 
         Response.End();
     }

  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM