Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using NPOI.HSSF.UserModel;
- using NPOI.SS.UserModel;
- using NPOI.XSSF.UserModel;
- using System.IO;
- using System.Web.Mvc;
- namespace ExcelExportMVCLab.Controllers
- {
- public class ExcelExportV2Controller : Controller
- {
- /// <summary>
- /// 副檔名為xls(Excel97-2003格式)
- /// </summary>
- public void ExportXls()
- {
- string fileName = "ExportData.xls";
- IWorkbook workbook = new HSSFWorkbook();
- ISheet sheet = workbook.CreateSheet("Sheet1");
- ExportExcel(workbook, fileName);
- }
- /// <summary>
- /// 副檔名為xlsx(Excel2007以上格式)
- /// </summary>
- public void ExportXlsx()
- {
- string fileName = "ExportData.xlsx";
- IWorkbook workbook = new XSSFWorkbook();
- ISheet sheet = workbook.CreateSheet("Sheet1");
- ExportExcel(workbook, fileName);
- }
- private void ExportExcel(IWorkbook workbook, string fileName)
- {
- using (MemoryStream ms = new MemoryStream())
- {
- workbook.Write(ms);
- Response.Clear();
- if(fileName.ToLower().EndsWith(".xls"))
- Response.ContentType = "application/vnd.ms-excel";
- else if (fileName.ToLower().EndsWith(".xlsx"))
- Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
- Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
- Response.BinaryWrite(ms.ToArray());
- Response.Flush();
- Response.End();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement