Advertisement
imjyb1008work

ExcelExportV2

May 22nd, 2019
1,195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.41 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 ExcelExportV2Controller : Controller
  10.     {
  11.         /// <summary>
  12.         /// 副檔名為xls(Excel97-2003格式)
  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.             ExportExcel(workbook, fileName);
  22.         }
  23.  
  24.         /// <summary>
  25.         /// 副檔名為xlsx(Excel2007以上格式)
  26.         /// </summary>
  27.         public void ExportXlsx()
  28.         {
  29.             string fileName = "ExportData.xlsx";
  30.  
  31.             IWorkbook workbook = new XSSFWorkbook();
  32.             ISheet sheet = workbook.CreateSheet("Sheet1");
  33.  
  34.             ExportExcel(workbook, fileName);
  35.         }
  36.  
  37.         private void ExportExcel(IWorkbook workbook, string fileName)
  38.         {
  39.             using (MemoryStream ms = new MemoryStream())
  40.             {
  41.                 workbook.Write(ms);
  42.            
  43.                 Response.Clear();
  44.                 if(fileName.ToLower().EndsWith(".xls"))
  45.                     Response.ContentType = "application/vnd.ms-excel";
  46.                 else if (fileName.ToLower().EndsWith(".xlsx"))
  47.                     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  48.                 Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
  49.                 Response.BinaryWrite(ms.ToArray());
  50.                 Response.Flush();
  51.                 Response.End();
  52.             }
  53.         }
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement