ExcelTemplate.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using NPOI.HSSF.UserModel;
  2. using NPOI.HPSF;
  3. using NPOI.HSSF.Util;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Web;
  11. using NPOI.SS.UserModel;
  12. using NPOI.XSSF.UserModel;
  13. namespace LeaRun.Util.Offices
  14. {
  15. public class ExcelTemplate
  16. {
  17. private string templatePath;
  18. private string newFileName;
  19. private string templdateName;
  20. private string sheetName;
  21. public string SheetName
  22. {
  23. get { return sheetName; }
  24. set { sheetName = value; }
  25. }
  26. public ExcelTemplate(string templdateName, string newFileName)
  27. {
  28. this.sheetName = "sheet1";
  29. templatePath = HttpContext.Current.Server.MapPath("/") + "/Resource/ExcelTemplate/";
  30. this.templdateName = string.Format("{0}{1}", templatePath, templdateName);
  31. this.newFileName = newFileName;
  32. }
  33. public void ExportDataToExcel(Action<ISheet> actionMethod)
  34. {
  35. using (MemoryStream ms = SetDataToExcel(actionMethod))
  36. {
  37. byte[] data = ms.ToArray();
  38. #region response to the client
  39. HttpResponse response = System.Web.HttpContext.Current.Response;
  40. response.Clear();
  41. response.Charset = "UTF-8";
  42. response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";
  43. System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + newFileName));
  44. System.Web.HttpContext.Current.Response.BinaryWrite(data);
  45. #endregion
  46. }
  47. }
  48. private MemoryStream SetDataToExcel(Action<ISheet> actionMethod)
  49. {
  50. //Load template file
  51. FileStream file = new FileStream(templdateName, FileMode.Open, FileAccess.Read);
  52. XSSFWorkbook workbook = new XSSFWorkbook(file);
  53. ISheet sheet = workbook.GetSheet(SheetName);
  54. if (actionMethod != null) actionMethod(sheet);
  55. sheet.ForceFormulaRecalculation = true;
  56. using (MemoryStream ms = new MemoryStream())
  57. {
  58. workbook.Write(ms);
  59. ms.Flush();
  60. //ms.Position = 0;
  61. return ms;
  62. }
  63. }
  64. }
  65. }