C#使用NPOI获取Word模板文档,并填充数据

 Word模板:原文档很长,这里只展示一部分

C#使用NPOI获取Word模板文档,并填充数据_第1张图片

填充数据之后:

C#使用NPOI获取Word模板文档,并填充数据_第2张图片

 两者对比

C#使用NPOI获取Word模板文档,并填充数据_第3张图片

关键代码

WordUtil.cs


using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using NPOI.XWPF.UserModel;
using ServiceStack.Text;
using Srm.Audit.Application.Contracts.RiskAssessmentForm;
using Srm.Core;


namespace Srm.Excel
{
    public class WordUtil
    {
        XWPFDocument document = null;
        public WordUtil(IFormFile file)
        {
            MemoryStream ms = new MemoryStream();
            file.OpenReadStream().CopyTo(ms);
            ms.Position = 0;
            string fileName = file.FileName;
            string fileType = fileName.Substring(fileName.LastIndexOf("."));
            try
            {
                if (".doc".Equals(fileType) || ".docx".Equals(fileType) || ".docm".Equals(fileType))
                {
                    document = new XWPFDocument(ms);
                }
                else
                {
                    throw new BusinessException("不支持这种格式");
                }
            }
            catch (Exception ex)
            {
                throw new BusinessException(ex.Message);
            }
        }

        public WordUtil(byte[] buffer, string fileName)
        {
            MemoryStream ms = new MemoryStream(buffer);
            if (ms == null)
            {
                throw new BusinessException("Word文件生成错误");
            }
            string fileType = fileName.Substring(fileName.LastIndexOf("."));
            try
            {
                if (".doc".Equals(fileType) || ".docx".Equals(fileType) || ".docm".Equals(fileType))
                {
                    document = new XWPFDocument(ms);
                }
                else
                {
                    throw new BusinessException("不支持这种格式");
                }
            }
            catch (Exception ex)
            {
                throw new BusinessException(ex.Message);
            }
        }

        public MemoryStream RiskAssessmentExport(SuppRiskFormDto suppRiskFormDto, CancellationToken cancellationToken)
        {
            byte[] bytes;
            MemoryStream ms = new MemoryStream();
            if (document == null)
            {
                throw new BusinessException("Workbook对象为空!");
            }
            var TableTestList = JsonConvert.DeserializeObject>>(suppRiskFormDto.TABLETEXTLIST);
            var TableCommentsList = JsonConvert.DeserializeObject>>(suppRiskFormDto.TABLECOMMENTSLIST);
            var TableCheckBoxList = suppRiskFormDto.TABLECHECKBOXLIST.Split(',');
            var CheckBoxList = suppRiskFormDto.CheckBoxlist.Split(',');
            var i = 0;
            var j =0;
            var k = 0;
            //遍历表格
            foreach (XWPFTable table in document.Tables)
            {
                foreach(XWPFTableRow row in table.Rows)
                {
                    foreach (XWPFTableCell cell in row.GetTableICells())
                    {
                        if (cell.GetText().Contains("${tabletxt}"))
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                // 替换 ${tabletxt}
                                string oldText = para.ParagraphText;
                                var newText = oldText.Replace("${tabletxt}", TableTestList[i].Get("txt"));
                                para.ReplaceText(oldText, newText);
                            }
                            i++;
                        }
                        else if (cell.GetText().Contains("${tabletexta}"))
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                string oldText = para.ParagraphText;
                                var newText = oldText.Replace("${tabletexta}", TableCommentsList[j].Get("txt"));
                                para.ReplaceText(oldText, newText);
                            }
                            j++;
                        }
                        //获取表格里面的选择框
                        else if (cell.GetText().Contains("${tc}"))
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                string oldText = para.ParagraphText;
                                var newText = "";
                                if(!oldText.IsNullOrEmpty())
                                {
                                    if (TableCheckBoxList[k].Equals("true"))
                                    {
                                        newText = oldText.Replace("${tc}", "☑");
                                    }
                                    else if (TableCheckBoxList[k].Equals("false"))
                                    {
                                        newText = oldText.Replace("${tc}", "☐");
                                    }
                                    para.ReplaceText(oldText, newText);
                                }                               
                            }
                            k++;
                        }
                    }
                }
            }
            //获取除表格外的选择框  替换这里的${ch}       
            //${ch}股份制 ${ch}私有制
            var ii = 0;
            foreach (var para in document.Paragraphs)
            {
                string oldText = para.ParagraphText;
                var newText = "";
                if (!oldText.IsNullOrEmpty())
                {
                    while (oldText.Contains("${ch}"))
                    {
                        if (CheckBoxList[ii].Equals("true"))
                        {
                            oldText = oldText.ReplaceFirst("${ch}", "☑");
                            ii++;
                        }
                        else if (CheckBoxList[ii].Equals("false"))
                        {
                            oldText = oldText.ReplaceFirst("${ch}", "☐");
                            ii++;
                        }
                    }
                    para.ReplaceText(para.ParagraphText, oldText);
                }
            }
            document.Write(ms);
            return ms;
        }     
    }
}

参考:使用NPOI导出复杂Word详解——C#篇_npoi导出word_迷幻的青春的博客-CSDN博客

C# 使用NPOI生成Word文档(按照模板) – 悠悠之家http://www.360doc.com/content/21/1108/12/30072234_1003268141.shtml

你可能感兴趣的:(c#,开发语言)