C# 用Spire根据word模板和插入的标签 填写数据并导出


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace SandInspect.Common
{
    public class Bookmark
    {

        private Document doc = null;
        public Bookmark(Document document)
        {
            doc = document;
        }

        /// 
        /// 用文本替换指定书签的内容
        /// 
        /// 书签名
        /// 文本
        /// 删除原始书签内容时,是否保留格式
        /// TextRange
        public Spire.Doc.Fields.TextRange ReplaceContent(string bookmarkName, string text, bool saveFormatting)
        {
            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            navigator.MoveToBookmark(bookmarkName);//指向特定书签
            navigator.DeleteBookmarkContent(saveFormatting);//删除原有书签内容     
            Spire.Doc.Interface.ITextRange textRange = navigator.InsertText(text);//写入文本
            return textRange as TextRange;
        }

        /// 
        /// 用图片替换指定书签的内容
        /// 
        /// 书签名
        /// 图片路径
        /// 宽度缩放比例,0以上正整数
        /// 高度缩放比例,0以上正整数
        /// 环绕方式
        /// 
        public void ReplaceContent(string bookmarkName, string picPath, float widthScale, float heightScale, TextWrappingStyle wrapStyle, ShapeHorizontalAlignment horizontalAlignment)
        {
            //BookmarksNavigator navigator = new BookmarksNavigator(doc);
            //navigator.MoveToBookmark(bookmarkName);
            //navigator.DeleteBookmarkContent(false);
            //IParagraphBase paragraphBase = navigator.InsertParagraphItem(ParagraphItemType.Picture);//插入类型为图片
            //Image image = Image.FromFile(picPath);//加载图片
            //DocPicture picture = paragraphBase.OwnerParagraph.AppendPicture(image);//插入图片
            ////picture.WidthScale = widthScale;
            ////picture.HeightScale = heightScale;
            ////picture.TextWrappingStyle = wrapStyle;
            //picture.HorizontalPosition = 0f;
            //picture.VerticalPosition = 0f;
            ////设置文字环绕方式           
            //picture.TextWrappingStyle = TextWrappingStyle.None;
            ////设置图片大小          
            //picture.Width = 160;
            //picture.Height = 160;
            //picture.HorizontalAlignment = horizontalAlignment;


            //创建BookmarksNavigator实例
            BookmarksNavigator bn = new BookmarksNavigator(doc);
            //找到名为Spire的书签
            bn.MoveToBookmark(bookmarkName, true, true);
            //添加一个secton并命名为section0
            Section section0 = doc.AddSection();
            //为section0添加一个段落
            Paragraph paragraph = section0.AddParagraph();
            paragraph.Text = "";
            //加载一张图片
            Image image = Image.FromFile(picPath);
            //为段落添加图片
            DocPicture picture = paragraph.AppendPicture(image);
            picture.HorizontalPosition = 0f;
            picture.VerticalPosition = 0f; //设置图像的停靠位置方式
            //设置图片大小          
            picture.Width = 145;
            picture.Height = 145;
            picture.HorizontalAlignment = ShapeHorizontalAlignment.Center;
            picture.TextWrappingStyle = TextWrappingStyle.None;

            //把含有图片的段落插入到书签位置
            bn.InsertParagraph(paragraph);
            doc.Sections.Remove(section0);


        }


        /// 
        /// 用图片替换指定书签的内容2
        /// 
        /// 书签名
        /// 图片路径
        /// 宽度缩放比例,0以上正整数
        /// 高度缩放比例,0以上正整数
        /// 环绕方式
        /// 
        public void ReplaceContent2(string bookmarkName, string picPath, float widthScale, float heightScale, TextWrappingStyle wrapStyle, ShapeHorizontalAlignment horizontalAlignment)
        {
            //创建BookmarksNavigator实例
            BookmarksNavigator bn = new BookmarksNavigator(doc);
            //找到名为Spire的书签
            bn.MoveToBookmark(bookmarkName, true, true);
            //添加一个secton并命名为section0
            Section section0 = doc.AddSection();
            //为section0添加一个段落
            Paragraph paragraph = section0.AddParagraph();
            paragraph.Text = "";
            //加载一张图片
            Image image = Image.FromFile(picPath);
            //为段落添加图片
            DocPicture picture = paragraph.AppendPicture(image);
            picture.HorizontalPosition = 0f;
            picture.VerticalPosition = 0f; //设置图像的停靠位置方式
            //设置图片大小          
            picture.Width = 300;
            picture.Height = 300;
            picture.HorizontalAlignment = ShapeHorizontalAlignment.Center;
            picture.TextWrappingStyle = TextWrappingStyle.None;

            //把含有图片的段落插入到书签位置
            bn.InsertParagraph(paragraph);
            doc.Sections.Remove(section0);


        }

        /// 
        /// 用表格替换指定书签的内容
        /// 
        /// 书签名
        /// Table实例
        public void ReplaceContent(string bookmarkName, Table table)
        {
            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            navigator.MoveToBookmark(bookmarkName);
            TextBodyPart body = new TextBodyPart(doc);
            body.BodyItems.Add(table);
            navigator.ReplaceBookmarkContent(body);
        }

        /// 
        /// 创建表格并写入数据,返回Table对象
        /// 
        /// 行数
        /// 列数
        /// 列宽
        /// 水平对齐方式
        /// DataTable实例
        /// 
        public Table CreateTable(int rowsNum, int columnsNum, float columnWidth, RowAlignment horizontalAlignment, System.Data.DataTable datatable)
        {
            Table table = new Table(doc, true, 1f);//初始化Table对象
            table.ResetCells(rowsNum, columnsNum);//设置行数和列数
            //填充数据
            for (int i = 0; i < datatable.Rows.Count; i++)
            {
                for (int j = 0; j < datatable.Columns.Count; j++)
                {
                    table.Rows[i].Cells[j].AddParagraph().AppendText(datatable.Rows[i][j].ToString());
                }
            }
            //设置列宽
            for (int i = 0; i < rowsNum; i++)
            {
                for (int j = 0; j < columnsNum; j++)
                {
                    table.Rows[i].Cells[j].Width = columnWidth;
                }
            }
            table.TableFormat.HorizontalAlignment = horizontalAlignment;//表格水平对齐方式
            return table;
        }

    }
}

Bookmark类代码

下面是调用方法 插入文字和图片

  public class WordModel
        {
            public string DH { get; set; }
            public string Url { get; set; }

            public string YSL { get; set; }

            public string YSLX { get; set; }

            public string BeginTime { get; set; }

            public string EndTime { get; set; }

            public string CLMS { get; set; }

            public string YSCMS { get; set; }

            public string SFGK { get; set; }

            public string MDGK { get; set; }

            public string Type { get; set; }

        }


        public ActionResult BatchOutPutWordBy(WordModel wm)
        {
            try
            {
               

                if (wm.Type == "1")//机制砂
                {
                    Document doc = new Document();
                    doc.LoadFromFile(Server.MapPath("~/UploadFiles/jzsword.docx"));
                    Common.Bookmark bookmark = new Common.Bookmark(doc);
                    bookmark.ReplaceContent("dh", wm.DH, true);
                    bookmark.ReplaceContent("ysl", wm.YSL, true);
                    bookmark.ReplaceContent("yslx", wm.YSLX, true);
                    bookmark.ReplaceContent("kssj", wm.BeginTime, true);
                    bookmark.ReplaceContent("jssj", wm.EndTime, true);
                    bookmark.ReplaceContent("clms", wm.CLMS, true);
                    bookmark.ReplaceContent("yscms", wm.YSCMS, true);
                    bookmark.ReplaceContent("sfgk", wm.SFGK, true);
                    bookmark.ReplaceContent("mdgk", wm.MDGK, true);

                    var s2 = wm.Url.Replace(TAppSettingManager.Get("ImgPath"), "~") ;
                    string picPath = Server.MapPath(s2);

                    bookmark.ReplaceContent("url", picPath, 25, 25, TextWrappingStyle.TopAndBottom, ShapeHorizontalAlignment.Center);
                    //生成Word文件
                    var name = wm.DH;
                    var yurl = TAppSettingManager.Get("ImgPath") + "/UploadFiles/words/" + name + ".PDF";
                    if (System.IO.File.Exists(yurl))
                    {
                        System.IO.File.Delete(yurl);
                    }
                    var str = Server.MapPath("~/UploadFiles/words/" + name + ".PDF");
                    doc.SaveToFile(str, FileFormat.PDF);
                    string path = TAppSettingManager.Get("ImgPath") + "/UploadFiles/words/" + name + ".PDF";
                    return Json_IsoksSuccess(path);
                }
                else
                {
                    Document doc = new Document();
                    doc.LoadFromFile(Server.MapPath("~/UploadFiles/ylword.docx"));
                    Common.Bookmark bookmark = new Common.Bookmark(doc);
                    bookmark.ReplaceContent("dh", wm.DH, true);
                    bookmark.ReplaceContent("ysl", wm.YSL, true);
                    bookmark.ReplaceContent("yslx", wm.YSLX, true);
                    bookmark.ReplaceContent("kssj", wm.BeginTime, true);
                    bookmark.ReplaceContent("jssj", wm.EndTime, true);
                    bookmark.ReplaceContent("clms", wm.CLMS, true);
                    var s2 = wm.Url.Replace(TAppSettingManager.Get("ImgPath"), "~");
                    string picPath = Server.MapPath(s2);

                    bookmark.ReplaceContent("url", picPath, 25, 25, TextWrappingStyle.TopAndBottom, ShapeHorizontalAlignment.Center);
                    //生成Word文件
                    var name = wm.DH;
                    var yurl = TAppSettingManager.Get("ImgPath") + "/UploadFiles/words/" + name + ".PDF";
                    if (System.IO.File.Exists(yurl))
                    {
                        System.IO.File.Delete(yurl);
                    }
                    var str = Server.MapPath("~/UploadFiles/words/" + name + ".PDF");
                    doc.SaveToFile(str, FileFormat.PDF);
                    string path = TAppSettingManager.Get("ImgPath") + "/UploadFiles/words/" + name + ".PDF";
                    return Json_IsoksSuccess(path);
                }
                    return Json_IsoksError("参数错误");
            }
            catch (Exception ex)
            {
                return Json_IsoksError(ex.Message);
            }
        }

需要引入 NPOI 和 Spire.Pdf    Spire.Doc     Spire.License