当前位置: 首页 > news >正文

c#集成npoi根据excel模板导出excel

NuGet中安装npoi

创建excel模板,替换其中的内容生成新的excel文件。

例子中主要写了这四种情况:

1、替换单个单元格内容;
2、替换横向多个单元格;
3、替换表格;
4、单元格中插入图片;

using System.IO;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.Diagnostics;public static void exportExcel(){string currentDirectory = System.AppDomain.CurrentDomain.BaseDirectory;string templatePath = currentDirectory + "/template.xlsx";string outputPath = currentDirectory + "/output/" + DateTime.Now.ToString("yyyyMMdd"); //存储路径string outputPathExcel = outputPath + "/" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_test.xlsx";// 检查路径是否存在if (!Directory.Exists(outputPath)){Directory.CreateDirectory(outputPath);}//1、单元格直接替换部分Dictionary<string, string> replacements = new Dictionary<string, string>{{ "test1", "测试1" },{ "test2", "测试2" }};//2、横向数组,曲线表格Dictionary<string, double[]> replacementsArrayH = = new Dictionary<string, double[]>();replacementsArrayH["item1"] = new double[] { 1.1, 2.2, 3.3 };replacementsArrayH["item2"] = new double[] { 4.4, 5.5, 6.6 };//3、表格数据//自己定义类//public TaskItem{//  private string name;//  private string age;//  public TaskItem(){//  }//  public TaskItem(string name, string age){//	  this.name=name;//	  this.age=age;//  }//  ……//}List<TaskItem> taskItemList = new List<TaskItem>();taskItemList.Add(new TaskItem("Alice", "30"));taskItemList.Add(new TaskItem("Bob", "25"));try{// excel导出using (FileStream file = new FileStream(templatePath, FileMode.Open, FileAccess.Read)){IWorkbook workbook = new XSSFWorkbook(file);ISheet sheet = workbook.GetSheetAt(0);// 替换模板中的字符串for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++){IRow row = sheet.GetRow(rowIndex);if (row == null){continue;}for (int cellIndex = 0; cellIndex < row.LastCellNum; cellIndex++){ICell cell = row.GetCell(cellIndex);if (cell != null && cell.CellType == CellType.String){string cellValue = cell.StringCellValue;//填充单个文本foreach (var replacement in replacements){if (cellValue.Equals(replacement.Key)){cell.SetCellValue(cellValue.Replace(replacement.Key, replacement.Value));}}//填充横向数组foreach (var replacement in replacementsArrayH){string placeholder = replacement.Key;double[] values = replacement.Value;int index = values.Length;if (cellValue.Equals(replacement.Key)){for (int colNum = 0; colNum < index; colNum++){cell = row.GetCell(cellIndex + colNum);cell.SetCellValue(cellValue.Replace(placeholder, values[colNum].ToString()));}}}//填充详情表格if (cellValue.Equals("table")){if (list == null) // list 为业务需要写入数据{continue;}// 添加数据行for (var i = 0; i < list.Count; i++){TaskItem item = list[i];// 因为模版内已经存在一格空行,所以直接赋值,后续从此行进行 CopyRow 即可if (i == 0){SetRowCellValue(row, item, cellIndex);continue;}//其他行var newRow = sheet.CopyRow(rowIndex, rowIndex + i);SetRowCellValue(newRow, item, cellIndex);}}}}}//4、导出图片string picPath = currentDirectory + "/test.png";//图片byte[] bytes = File.ReadAllBytes(picPath);int pictureIndex = workbook.AddPicture(bytes, PictureType.PNG);// 定义图片的位置var drawingPatriarch = sheet.CreateDrawingPatriarch();var anchor = drawingPatriarch.CreateAnchor(0, 0, 0, 0, 1, 6, 12, 13); // 参数依次是:dx1, dy1, dx2, dy2, col1, row1, col2, row2// 在单元格中添加图片var picture = drawingPatriarch.CreatePicture(anchor, pictureIndex);// 保存新文件using (FileStream outputFile = new FileStream(outputPathExcel, FileMode.Create, FileAccess.Write)){workbook.Write(outputFile);}}}catch (Exception ex){}}/// <summary>/// 填充表格数据/// </summary>/// <param name="row">填充行</param>/// <param name="item">填充数据</param>/// <param name="cellIndex">列开始行</param>private static void SetRowCellValue(IRow row, TaskItem item, int cellIndex){ICell cell = row.GetCell(cellIndex++);cell.SetCellValue(item.name);cellIndex++;cell = row.GetCell(cellIndex++);cell.SetCellValue(item.age);}

excel模板内容:

导出后:

http://www.lryc.cn/news/517325.html

相关文章:

  • Vue2移动端(H5项目)项目封装switch组件支持动态设置开启关闭背景色、值及组件内显示文字描述、禁用、switch 的宽度
  • MATLAB语言的语法糖
  • 数字IC设计高频面试题
  • OpenCV 4.5至4.10版本更新概述
  • OSPF - LSA对照表
  • 游戏引擎学习第77天
  • 【项目实战1】五子棋游戏
  • HTML5 动画效果:淡入淡出(Fade In/Out)详解
  • Conmi的正确答案——Cordova使用“src-cordova/config.xml”编辑“Android平台”的“uses-permission”
  • 在Mysql环境下对数据进行增删改查
  • Spring 设计模式:经典设计模式
  • OneFlow和PyTorch在性能上有哪些区别?
  • win下搭建elk并集成springboot
  • H7-TOOL固件2.27发布,新增加40多款芯片脱机烧录,含多款车轨芯片,发布LUA API手册,CAN助手增加负载率,错误状态信息检测
  • STM32+WIFI获取网络时间+8位数码管显示+0.96OLED显
  • 以太网ICMP协议(ping指令)——FPGA学习笔记25
  • 从零手写线性回归模型:PyTorch 实现深度学习入门教程
  • 【Cesium】自定义材质,添加带有方向的滚动路线
  • C 语言奇幻之旅 - 第11篇:C 语言动态内存管理
  • IDEA 撤销 merge 操作(详解)
  • swarm天气智能体调用流程
  • LED背光驱动芯片RT9293应用电路
  • 二叉树的二叉链表和三叉链表
  • 【学习路线】Python 算法(人工智能)详细知识点学习路径(附学习资源)
  • C++直接内存管理new和delete
  • Linux 内核中网络接口的创建与管理
  • 人工智能 前馈神经网络练习题
  • Windows搭建RTMP服务器
  • Vue重新加载子组件
  • 【VScode】设置代理,通过代理连接服务器