Advertisement
imjyb1008work

ExcelExport

May 22nd, 2019
1,897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.SS.UserModel;
  3. using NPOI.XSSF.UserModel;
  4. using System.IO;
  5. using System.Web.Mvc;
  6.  
  7. namespace ExcelExportMVCLab.Controllers
  8. {
  9.     public class ExcelExportController : Controller
  10.     {
  11.         /// <summary>
  12.         /// 副檔名為xls請使用此
  13.         /// </summary>
  14.         public void ExportXls()
  15.         {
  16.             string fileName = "ExportData.xls";
  17.  
  18.             IWorkbook workbook = new HSSFWorkbook();
  19.             ISheet sheet = workbook.CreateSheet("Sheet1");
  20.  
  21.             using (MemoryStream ms = new MemoryStream())
  22.             {
  23.                 workbook.Write(ms);
  24.                 Response.Clear();
  25.                 Response.ContentType = "application/vnd.ms-excel";
  26.                 Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
  27.                 Response.BinaryWrite(ms.ToArray());
  28.                 Response.Flush();
  29.                 Response.End();
  30.                 workbook = null;   
  31.             }
  32.         }
  33.  
  34.         /// <summary>
  35.         /// 副檔名為xlsx請使用此
  36.         /// </summary>
  37.         public void ExportXlsx()
  38.         {
  39.             string fileName = "ExportData.xlsx";
  40.  
  41.             IWorkbook workbook = new XSSFWorkbook();
  42.             ISheet sheet = workbook.CreateSheet("Sheet1");
  43.  
  44.             using (MemoryStream ms = new MemoryStream())
  45.             {
  46.                 workbook.Write(ms);
  47.                 Response.Clear();
  48.                 Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  49.                 Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
  50.                 Response.BinaryWrite(ms.ToArray());
  51.                 Response.Flush();
  52.                 Response.End();
  53.             }
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement