环境:net framework 4.5.2


    效果图

    1. /// <summary>
    2. /// Excel模板自定义常用设置 当前方法仅支持xlsx版本XSSFWorkbook,百度大多都是HSSFWorkbook(xls)
    3. /// </summary>
    4. /// <param name="b"></param>
    5. /// <param name="relativePath"></param>
    6. /// <param name="rename"></param>
    7. /// <returns></returns>
    8. public override string Down(ControllerBase b, string relativeName, string rename) {
    9. //路径验证
    10. DirectoryInfo dir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + this.BaseDirectory);
    11. if (!dir.Exists) dir.Create();
    12. relativeName = AppDomain.CurrentDomain.BaseDirectory + this.BaseDirectory + relativeName;
    13. FileInfo file = new FileInfo(relativeName);
    14. if (file.Exists) file.Delete();
    15. //创建文件流
    16. using (FileStream fs = new FileStream(relativeName, FileMode.Create)) {
    17. //创建空对象
    18. //IWorkbook book = Path.GetExtension(relativeName).ToLower() == ".xlsx" ? new XSSFWorkbook() : new HSSFWorkbook();
    19. IWorkbook book = new XSSFWorkbook();
    20. //创建模板
    21. ISheet et = book.CreateSheet("Drmwe");
    22. //表格线
    23. et.DisplayGridlines = false;
    24. //设置表头
    25. for (int i = 0; i < 4; i++) {
    26. var irow = et.CreateRow(i);
    27. for (int j = 0; j < 6; j++) {
    28. var str = irow.CreateCell(j);
    29. XSSFCellStyle style = (XSSFCellStyle)book.CreateCellStyle();
    30. //填充默认背景色
    31. style.SetFillForegroundColor(new XSSFColor(Color.Black));
    32. style.FillPattern = FillPattern.SolidForeground;
    33. //这个填充的是鼠标编辑才变颜色 - 不编辑不会出现设置的颜色
    34. //style.SetFillBackgroundColor(new XSSFColor(Color.Black));
    35. str.CellStyle = style;
    36. }
    37. }
    38. //合并单元格
    39. et.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 3, 0, 5));
    40. //创建路径文件流读取
    41. var path = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Photo/wemes.png");
    42. FileStream titleFs = path.OpenRead();
    43. //FileStream titleFs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "Photo/wemes.png", FileMode.Open, FileAccess.Read);
    44. int filelength = (int)titleFs.Length; //获得文件长度
    45. Byte[] image = new Byte[filelength]; //建立一个字节数组
    46. titleFs.Read(image, 0, filelength); //按字节流读
    47. //创建绘画基类
    48. var patriarch = (XSSFDrawing)et.CreateDrawingPatriarch();
    49. //图片定位
    50. XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, 0, 0, 6, 4);
    51. //等比缩小
    52. anchor.AnchorType = AnchorType.MoveAndResize;
    53. //把图片插到相应的位置
    54. patriarch.CreatePicture(anchor, book.AddPicture(image, PictureType.PNG));
    55. //关闭标题文件流读取
    56. titleFs.Close();
    57. //创建标题
    58. for (int i = 4; i < 7; i++) {
    59. var irow = et.CreateRow(i);
    60. for (int j = 0; j < 6; j++) {
    61. irow.CreateCell(j);
    62. }
    63. }
    64. //合并
    65. et.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(4, 6, 0, 5));
    66. //设置标题
    67. var title = et.GetRow(4).GetCell(0);
    68. title.SetCellValue("Demo测试模板");
    69. XSSFCellStyle titleStyle = (XSSFCellStyle)book.CreateCellStyle();
    70. var titleFont = (XSSFFont)book.CreateFont();
    71. //字体大小
    72. titleFont.FontHeightInPoints = 20;
    73. titleFont.IsBold = true;
    74. titleStyle.SetFont(titleFont);
    75. //居中
    76. titleStyle.VerticalAlignment = VerticalAlignment.Center;//垂直居中 方法1
    77. titleStyle.Alignment = HorizontalAlignment.Center;//水平居中 方法2
    78. //titleStyle.Alignment = HorizontalAlignment.CenterSelection;//水平居中 方法3
    79. title.CellStyle = titleStyle;
    80. //副标题创建
    81. for (int i = 7; i < 8; i++) {
    82. var irow = et.CreateRow(i);
    83. //设置行高
    84. //在Excel中,每一行的高度也是要求一致的,所以设置单元格的高度,其实就是设置行的高度,所以相关的属性也应该在HSSFRow上,它就是HSSFRow.Height和HeightInPoints,
    85. //这两个属性的区别在于HeightInPoints的单位是点,而Height的单位是1 / 20个点,所以Height的值永远是HeightInPoints的20倍。
    86. //irow.Height = 25 * 20;
    87. irow.HeightInPoints = 25;
    88. for (int j = 0; j < 6; j++) {
    89. irow.CreateCell(j);
    90. }
    91. }
    92. //合并
    93. et.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 7, 0, 1));
    94. et.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 7, 2, 3));
    95. et.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(7, 7, 4, 5));
    96. //设置副标题
    97. et.GetRow(7).GetCell(0).SetCellValue("编号1:");
    98. et.GetRow(7).GetCell(2).SetCellValue("编号2:");
    99. et.GetRow(7).GetCell(4).SetCellValue("编号3:");
    100. //第九行行高设置小点
    101. var irow_9 = et.CreateRow(8);
    102. irow_9.Height = 5 * 20;
    103. //为了保证数据准确性创建 查询数据库
    104. var sfc = new BaseDataAccess("sfc");
    105. var dataSource = sfc.db.SqlQueryable<object>(@"select top(10) a.NAME as '产品名称',b.LOT_NAME as '工单名称',c.NAME as '工艺流程',d.CUSTOMER_NAME as '客户名称',b.QUANTITY as '工单数量' from
    106. QS_PRODUCTS a join QS_LOTS b on a.PRODUCT_ID = b.PRODUCT_ID join QS_ROUTES c on a.ROUTE_ID = c.ROUTE_ID
    107. join QS_CUSTOMERS d on a.CUSTOMER_CODE = d.CUSTOMER_CODE order by a.CREATE_TIME desc").ToDataTable();
    108. //留出一行 所有行 + 自己的标题
    109. for (int i = 9; i < (dataSource.Rows.Count + 10); i++) {
    110. var irow = et.CreateRow(i);
    111. irow.HeightInPoints = 20;
    112. for (int j = 0; j < dataSource.Columns.Count + 1; j++) {
    113. var icell = irow.CreateCell(j);
    114. var dataStyle = book.CreateCellStyle();
    115. dataStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; //下边框线
    116. dataStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; //左边框线
    117. dataStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; //右边框线
    118. dataStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; //上边框线
    119. //内容垂直 水平居中
    120. dataStyle.VerticalAlignment = VerticalAlignment.Center;
    121. dataStyle.Alignment = HorizontalAlignment.Center;
    122. //文字换行
    123. dataStyle.WrapText = true;
    124. icell.CellStyle = dataStyle;
    125. //设置标题
    126. if (i == 9 && j == 0) icell.SetCellValue("序号");
    127. else if (i == 9) icell.SetCellValue(dataSource.Columns[j - 1].ColumnName);
    128. else {
    129. //设置下标
    130. int dataIndex = i - dataSource.Rows.Count;
    131. //插入数据源
    132. if (j == 0) icell.SetCellValue((dataIndex + 1).ToString());
    133. else icell.SetCellValue(dataSource.Rows[dataIndex][j - 1].ToString());
    134. }
    135. }
    136. }
    137. //获取最后一行
    138. var lastIndex = et.LastRowNum + 1;
    139. //填充标脚
    140. var footerRow = et.CreateRow(lastIndex);
    141. //创建列
    142. for (int i = 0; i < 6; i++) footerRow.CreateCell(i);
    143. //设置当前行高
    144. footerRow.HeightInPoints = 25;
    145. //合并
    146. et.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(lastIndex, lastIndex, 1, 3));
    147. et.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(lastIndex, lastIndex, 4, 5));
    148. //填充内容
    149. var dateCell = footerRow.GetCell(1);
    150. dateCell.SetCellValue($"Date:{DateTime.Now.ToString("yyyy-MM-dd")}");
    151. var userCell = footerRow.GetCell(4);
    152. userCell.SetCellValue("User:梁非凡");
    153. //设置通用样式
    154. var footerCellStyle = book.CreateCellStyle();
    155. var footerCellFont = book.CreateFont();
    156. footerCellFont.FontName = "仿宋";
    157. footerCellFont.Boldweight = (short)400;
    158. footerCellFont.FontHeightInPoints = (short)14;
    159. footerCellStyle.Alignment = HorizontalAlignment.Left;
    160. footerCellStyle.VerticalAlignment = VerticalAlignment.Center;
    161. footerCellStyle.SetFont(footerCellFont);
    162. dateCell.CellStyle = footerCellStyle;
    163. userCell.CellStyle = footerCellStyle;
    164. //设置表格是否加锁 IsLocked默认为true,需要配合表格方法ProtectSheet才能生效,如果指定行不想加锁,需设置行的IsLocked = false
    165. //footerCellStyle.IsLocked = true;
    166. et.ProtectSheet("lff");
    167. book.Write(fs);
    168. //习惯性关闭
    169. fs.Close();
    170. }
    171. return "";
    172. }