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

C# 使用NPOI生成Word文件

NuGet 安装 NPOI

1. 建立模板(可选): 手动建立Word模板, 多使用表格然后隐藏边框, 方便数据插入固定位置

2. 建立Word对象引入模板

string dPath = $"{Environment.CurrentDirectory}\\Data\\Demo.docx";
Stream fs = new FileStream(dPath, FileMode.Open);
XWPFDocument document = new XWPFDocument(fs);

3. 段落插入

public void Main()
{string dPath = $"{Environment.CurrentDirectory}\\Data\\Demo.docx";Stream fs = new FileStream(dPath, FileMode.Open);XWPFDocument document = new XWPFDocument(fs);AddParagraph(document, 0, 2, 2, AddPlaceholder(a1));AddParagraph(document, 0, 3, 2, AddPlaceholder(a2));AddParagraph(document, 0, 4, 2, AddPlaceholder(a3));
}
/// <summary>
/// 表格内插入段落
/// </summary>
/// <param name="document">模板对象</param>
/// <param name="TabIndex">表格序号</param>
/// <param name="Row"></param>
/// <param name="Cell"></param>
/// <param name="value">插入数据</param>
/// <returns></returns>
public XWPFParagraph AddParagraph(XWPFDocument document, int TabIndex, int Row, int Cell, string value)
{XWPFParagraph paragraph = document.Tables[TabIndex].GetRow(Row).GetCell(Cell).Paragraphs[0]; //创建段落对象paragraph.Alignment = ParagraphAlignment.CENTER;//文字显示位置,段落排列(左对齐,居中,右对齐)XWPFRun xwpfRun = paragraph.CreateRun();//创建段落文本对象xwpfRun.SetText(value);//填充内容xwpfRun.FontSize = 14;//设置文字大小xwpfRun.IsItalic = false;//是否设置斜体(字体倾斜)//xwpfRun.SetColor(fontColor);//设置字体颜色--十六进制xwpfRun.SetFontFamily("宋体", FontCharRange.None); //设置标题样式如:(微软雅黑,隶书,楷体)根据自己的需求而定return paragraph;
}

4. 插入图片

table = document.Tables[4];XWPFTableCell Cell = table.GetRow(1).GetCell(0);
XWPFParagraph p = Cell.Paragraphs[0];
XWPFRun run = p.CreateRun();
using (FileStream file = File.Open($"{PDFpath}.png", FileMode.OpenOrCreate))
{run.AddPicture(file, (int)NPOI.XWPF.UserModel.PictureType.PNG, "1.png", 5100000, 3000000);
}

5. 保存文件

sting SavePath = $"{Environment.CurrentDirectory}\\TestData\\{TestProject.ProjectName}\\{ObjectName}.docx";
using (FileStream fswrite = File.Open(SavePath, FileMode.OpenOrCreate))
{document.Write(fswrite);
}document.Close();

 

http://www.hskmm.com/?act=detail&tid=34986

相关文章:

  • 随机生成动态头像
  • element 表单校验失败定位到指定元素
  • 2025年湖北武汉实验室设计哪家口碑好/哪家信誉好/哪家售后好?
  • 国产化Word处理控件Spire.Doc教程:用Java实现TXT文本与Word互转的完整教程
  • C# Avalonia 16- Animation- BombDropper
  • 2025年太阳能板定制厂家可靠推荐与排行榜
  • 实验室改造推荐厂家/实验室设计供应商推荐/实验室装修找哪个?
  • 2025年太阳能板定制厂家口碑排行榜单:权威推荐与选择指南
  • 2025年太阳能板定制厂家口碑排行榜前十强:专业评测与选择指南
  • 2025年AI搜索优化品牌推荐排行榜前十强深度解析
  • 2025年AI搜索优化品牌推荐排行榜:技术深度解析与选择指南
  • 2025年AI搜索优化品牌排行榜前十强权威发布
  • 直播回顾|PostgreSQL 18 六大新特性深度解析
  • win10 开启大小核心调度--异类策略0~4介绍
  • 异常----Windows 已保护你的电脑:Microsoft Defender SmartScreen 阻止了无法识别的应用启动。运行此应用可能会导致你的电脑存在风险。
  • 把“扔硬币”搬到互联网:一文看懂 AB 测试的底层逻辑 - 指南
  • 记录下,cadence17.4 PCB封装更新方法
  • springboot使用aop切面,记录日志
  • 【整活】OI的那些奇妙小操作(Part 1)
  • 想学习的数学
  • qzmoot 生活合集
  • OO之接口-DAO模式代码阅读及应用
  • 个微协议,微信号二次开发/ipad协议
  • Win11设置默认打开全部右键菜单
  • 发现概率
  • 微信机器人开发API!3步搞定微信聊天机器人
  • yocto工程升级要点
  • windows2019的域控服务器更新时间.251020
  • 国内DOH解析速度测试(阿里 腾讯 360 Doh测速)
  • WatchAlert 轻量级AI日志告警 - Docker安装部署