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

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);}}}
}

*
*
*
*
*
*

相关文章:

  • 【Qt开发】信号与槽
  • 计数循环java
  • agentmain对业务的影响
  • 解构认知边界:论万能方法的本体论批判与方法论重构——基于跨学科视阈的哲学-科学辩证
  • 小白成长之路-vim编辑
  • 解锁Python TDD:从理论到实战的高效编程之道(9/10)
  • curl发送数据不为null,但是后端接收到为null
  • 界面组件DevExpress WPF中文教程:Grid - 如何自定义Band Header外观?
  • 里氏替换原则:Java 面向对象设计的基石法则
  • 鸿蒙 Core File Kit(文件基础服务)之简单使用文件
  • 【Bug】多文件上传只有最后一个loading会关闭
  • Ubuntu 上安装 FTP 服务、开放指定端口并创建用户
  • vue3学习——组合式 API:生命周期钩子
  • 电机控制储备知识学习(一) 电机驱动的本质分析以及与磁相关的使用场景
  • FFmpeg在Android开发中的核心价值是什么?
  • 串口模块详细讲解
  • Python-简单网络编程 I
  • 论文精读:YOLO-UniOW: Efficient Universal Open-World Object Detection
  • MES管理系统构建智能制造时代下的全面质量管理体系
  • Spring事务失效的全面剖析
  • 澎湃思想周报|欧洲胜利日之思;教育监控与学生隐私权争议
  • 新造古镇丨乌镇的水太包容了,可以托举住任何一种艺术
  • 十大券商看后市|A股中枢有望逐步震荡抬升,把握结构性行情
  • “海豚音”依旧互动更多,玛丽亚·凯莉本周来沪开唱
  • “80后”李灿已任重庆市南川区领导,此前获公示拟提名为副区长人选
  • 重庆一高校75万采购市价299元产品?工作人员:正在处理