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

NPOI 操作 Word 文档

管理 NuGet 程序包

# word操作
NPOI# 图片操作
SkiaSharp

Controller代码

using Microsoft.AspNetCore.Mvc;
using NPOI.Util;
using NPOI.XWPF.Model;
using NPOI.XWPF.UserModel;
using SkiaSharp;namespace WebApplication2.Controllers
{[Route("api/Npoi/[action]")][ApiController]public class NpoiController : ControllerBase{public NpoiController() { }[HttpPost("import")]public async Task<IActionResult> Import(IFormFile file){/// 创建文件夹var fileFolder = Path.Combine("File", "ExcelTemp");if (!Directory.Exists(fileFolder))Directory.CreateDirectory(fileFolder);string filePath = string.Empty;string[] LimitPictureType = { ".DOC", ".DOCX" };/// 获取word文档后缀是否存在数组中string currentPictureExtension = Path.GetExtension(file.FileName).ToUpper();if (LimitPictureType.Contains(currentPictureExtension)){List<WaterData> WaterDataList = new List<WaterData>();/// 读取上传文档保存到文件流var fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(file.FileName)}";var fileNameNew = $"{DateTime.Now.ToString("yyyyMMddHHmmss")}New{Path.GetExtension(file.FileName)}";filePath = Path.Combine(fileFolder, fileName);using (var stream = new FileStream(filePath, FileMode.Create)){await file.CopyToAsync(stream);}/// 读取文档内容using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)){XWPFDocument doc = new XWPFDocument(fs);/// 文档内容var body = doc.BodyElements.Count;/// 段落总数总数var paragraphs = doc.Paragraphs.Count;/// 表格总数var tables = doc.Tables.Count;/// 图片总数var pictures = doc.AllPictures.Count;/// 循环文档中的所有段落/// 注意图片会当做文本,只是text是空if (paragraphs > 0){for (int i = 0; i < paragraphs; i++){var paragraph = doc.Paragraphs[i];var text = paragraph.Text;}//foreach (XWPFParagraph paragraph in doc.Paragraphs)//{//    /// 获取段落的文本内容//    string paragraphText = paragraph.Text;//    var style = paragraph.Style;//}}/// 循环table表格内容if (tables > 0){for (int i = 0; i < tables; i++){XWPFTable table = doc.Tables[i];if (table.ElementType == BodyElementType.TABLE){var rows = table.NumberOfRows;for (int j = 1; j < table.Rows.Count; j++){var waterData = new WaterData();var tableCells = table.Rows[j].GetTableCells();waterData.name = tableCells[0].GetText();waterData.date = tableCells[1].GetText();waterData.wl = tableCells[2].GetText();waterData.fr = tableCells[3].GetText();waterData.source = "";WaterDataList.Add(waterData);}}}}/// 循环图片内容if (pictures > 0){for (int i = 0; i < pictures; i++){XWPFPictureData picData = doc.AllPictures[i];}}/// 修改文档内容,添加 n个 新段落XWPFParagraph new_p1 = doc.CreateParagraph();XWPFRun run1 = new_p1.CreateRun();run1.AddBreak(); // 添加换行符run1.SetText("这是新段落:第1行。");XWPFParagraph new_p2 = doc.CreateParagraph();XWPFRun run2 = new_p2.CreateRun();run2.AddBreak(); // 添加换行符run2.SetText("这是新段落:第2行");#region 复制段落1,并添加到新文档中// 复制段落,并添加到新文档中XWPFParagraph new_copy_p3 = doc.CreateParagraph();foreach (var run in doc.Paragraphs[1].Runs){XWPFRun newCopyRun = new_copy_p3.CreateRun();newCopyRun.SetText(run.Text); // 设置文本内容newCopyRun.FontFamily = run.FontFamily; // 复制字体家族newCopyRun.FontSize = run.FontSize;     // 复制字体大小newCopyRun.IsBold = run.IsBold;         // 复制粗体样式newCopyRun.IsItalic = run.IsItalic;     // 复制斜体样式newCopyRun.Underline = run.Underline;   // 复制下划线样式newCopyRun.SetColor(run.GetColor());    // 复制字体颜色}#endregion#region 复制段落2,并添加到新文档中XWPFParagraph new_copy_p4 = doc.CreateParagraph();foreach (var run in doc.Paragraphs[1].Runs){XWPFRun destRun = new_copy_p4.CreateRun();CopyRunStyle(run, destRun);}#endregion#region 插入图片// 图片路径string imagePath = @"E:\107.png";XWPFParagraph new_image_p5 = doc.CreateParagraph();XWPFRun imageP5Run = new_image_p5.CreateRun();InsertImg(imageP5Run, imagePath, "aaaa.jpg");#endregion#region 复制段落图片/// 创建一个段落XWPFParagraph new_image_p6 = doc.CreateParagraph();XWPFRun imageP6Run = new_image_p6.CreateRun();XWPFPictureData picture = doc.AllPictures[0];/// 复制方式1imageP6Run.AddPicture(new MemoryStream(picture.Data), picture.GetPictureType(), picture.FileName, 100 * 9525, 100 * 9525);/// 复制方式2byte[] pictureData = IOUtils.ToByteArray(picture.GetPackagePart().GetInputStream()); // 获取图片数据imageP6Run.AddPicture(new MemoryStream(pictureData), picture.GetPictureType(), picture.FileName, 100 * 9525, 100 * 9525);foreach (var item in doc.BodyElements){if (item.ElementType == BodyElementType.PARAGRAPH){var paragraph = (XWPFParagraph)item;foreach (var itemSon in paragraph.Runs){var tempPic = itemSon.GetEmbeddedPictures();if (tempPic != null && tempPic.Count > 0){}}}}#endregion/// 页眉页脚CreateHeaderFooter(doc, "页眉内容", "页脚内容");// 保存到新文档using (FileStream outStream = new FileStream(fileNameNew, FileMode.Create, FileAccess.Write)){doc.Write(outStream);}}}return Ok();}/// <summary>/// 复制段落样式等属性/// </summary>/// <param name="srcRun">源</param>/// <param name="destRun">目标</param>private void CopyRunStyle(XWPFRun srcRun, XWPFRun destRun){destRun.SetText(srcRun.Text);                     // 设置文本内容destRun.FontFamily = srcRun.FontFamily;           // 字体类型destRun.FontSize = srcRun.FontSize;               // 字体大小destRun.IsBold = srcRun.IsBold;                   // 粗体样式destRun.IsItalic = srcRun.IsItalic;               // 斜体样式destRun.Underline = srcRun.Underline;             // 下划线类型destRun.SetStrike(srcRun.IsStrike);               // 是否删除线destRun.IsStrikeThrough = srcRun.IsStrikeThrough; // 是否删除线destRun.SetColor(srcRun.GetColor());              // 字体颜色destRun.IsCapitalized = srcRun.IsCapitalized;destRun.TextPosition = srcRun.TextPosition;       // 文本位置destRun.IsShadowed = srcRun.IsShadowed;           // 阴影destRun.IsEmbossed = srcRun.IsEmbossed;           // 浮雕}/// <summary>/// 页眉页脚/// </summary>/// <param name="doc"></param>/// <param name="headerText"></param>/// <param name="footerText"></param>private void CreateHeaderFooter(XWPFDocument doc, string headerText, string footerText){/// 添加页眉页脚策略XWPFHeaderFooterPolicy headerFooterPolicy = doc.CreateHeaderFooterPolicy();if (!string.IsNullOrWhiteSpace(headerText)){/// 添加页眉XWPFHeader header = headerFooterPolicy.CreateHeader(XWPFHeaderFooterPolicy.DEFAULT);XWPFParagraph headerParagraph = header.CreateParagraph();headerParagraph.VerticalAlignment = TextAlignment.CENTER;headerParagraph.Alignment = ParagraphAlignment.CENTER;  // 居中对齐headerParagraph.BorderBottom = Borders.Single;          // 边线XWPFRun headerRun = headerParagraph.CreateRun();headerRun.SetText(headerText);                          // 设置页脚文本//headerRun.SetFontFamily("Arial", FontCharRange.None); // 设置字体//headerRun.IsBold = true;                              // 设置粗体//headerRun.SetColor("000000");                         // 设置颜色(黑色)}if (!string.IsNullOrWhiteSpace(footerText)){// 添加页脚XWPFFooter footer = headerFooterPolicy.CreateFooter(XWPFHeaderFooterPolicy.DEFAULT);XWPFParagraph footerParagraph = footer.CreateParagraph();footerParagraph.VerticalAlignment = TextAlignment.CENTER;footerParagraph.Alignment = ParagraphAlignment.CENTER;   // 居中对齐footerParagraph.BorderBottom = Borders.Single;           // 边线XWPFRun footerRun = footerParagraph.CreateRun();footerRun.SetText(footerText);                           // 设置页脚文本//footerRun.SetFontFamily("Arial", FontCharRange.None);  // 设置字体//footerRun.IsBold = true;                               // 设置粗体//footerRun.SetColor("000000");                          // 设置颜色(黑色)}}/// <summary>/// 插入图片/// </summary>/// <param name="para"></param>/// <param name="imgpath"></param>private void InsertImg(XWPFRun run, string imgpath, string imgName){int width = 100;int height = 100;using (var imageData = SKImage.FromEncodedData(imgpath)){if (imageData != null){width = imageData.Width;height = imageData.Height;}}using (FileStream fsImg = new FileStream(imgpath, FileMode.OpenOrCreate, FileAccess.Read)){/// 长和宽必须乘上9525run.AddPicture(fsImg, (int)NPOI.XWPF.UserModel.PictureType.PNG, fsImg.Name, width * 9525, height * 9525);}}}
}

*
*
*
*
*
*

http://www.xdnf.cn/news/5786.html

相关文章:

  • 如何避免和恢复因终端关闭导致的 LoRA 微调中断
  • 用 VS Code / PyCharm 编写你的第一个 Python 程序
  • Java鼠标事件监听器MouseListener、MouseMotionListener和MouseWheelListener
  • Redis——线程模型·
  • Ubuntu 18.04.6下OpenSSL与OpenSSH版本升级
  • OptiStruct的转子临界转速分析
  • 解密企业级大模型智能体Agentic AI 关键技术:MCP、A2A、Reasoning LLMs- GPT源代码解析
  • [Java实战]Spring Boot 3 整合 Apache Shiro(二十一)
  • ubuntu----100,常用命令2
  • Python 字典键 “三变一” 之谜
  • 理解 C# 中的各类指针
  • OCR:开启财务数字化变革的魔法钥匙
  • Leetcode 3547. Maximum Sum of Edge Values in a Graph
  • swift flask python ipad当电脑键盘 实现osu x键和z键 长按逻辑有问题 quart 11毫秒
  • Spark 缓存(Caching)
  • 2025年PMP 学习十一 第8章 项目质量管理(8.3)
  • 运行Spark程序-在Idea中
  • 基于智能家居项目 实现DHT11驱动源代码
  • Linux目录和文件
  • idea Maven 打包SpringBoot可执行的jar包
  • C语言 ——— 函数栈帧的创建和销毁
  • Qt6.5.3 windows下安装教程
  • c++STL-list的使用和迭代器
  • 【AIGC 温柔档案】:镂空蕾丝与柔和线条的唯美算法融合
  • PostgreSQL 配置设置函数
  • MySQL 8.0 OCP 英文题库解析(四)
  • STM32 修炼手册
  • PostgreSQL 服务器信号函数
  • 设计模式深度解析:AI大模型下的策略模式与模板方法模式对比解析
  • 力扣HOT100之二叉树:543. 二叉树的直径