c#调用word com组件 替换书签套打

安装office2007,添加com引用Microsoft Word12.0 Object Library和Microsoft Office12.0 Object Library

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Data;

namespace CunJuInformationPlatformDataService.CommonClass
{
    public class WordAPI
    {
        public static  Paragraph AddParagraph(DocumentClass wordDoc, string contentTxt,WdParagraphAlignment align=WdParagraphAlignment.wdAlignParagraphLeft,int fontBold=1,int fontSize=12)
        {
            //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
            Object Nothing = System.Reflection.Missing.Value;//创建文档

            //  ////////////////////////////////
            //Insert a paragraph at the beginning of the document
            Microsoft.Office.Interop.Word.Paragraph myparagraph1;
            myparagraph1 = wordDoc.Content.Paragraphs.Add(ref Nothing);
            myparagraph1.Range.Text = contentTxt; //换3行显示123
            myparagraph1.Alignment = align; //段落居左
            myparagraph1.Range.Font.Bold = fontBold;
            myparagraph1.Range.Font.Size = fontSize;
            myparagraph1.Format.SpaceAfter = 24; //距离下一段的下边距(margin-bottom,单位是pt)
            myparagraph1.Range.InsertParagraphAfter();

            return myparagraph1;
        }

        public static void AddImage(DocumentClass wordDoc,string imgPath,float width=-1,float height=-1)
        {
            object oEndOfDoc = "\\endofdoc";/*预置书签表示文档结尾,原文有错误反斜杠写成了//正斜杠,导致下面的myrange有问题*/
            object myrange = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            //定义该插入的图片是否为外部链接
            Object linkToFile = false;                //默认
            //定义要插入的图片是否随Word文档一起保存
            Object saveWithDocument = true;               //默认
            //使用InlineShapes.AddPicture方法插入图片
            wordDoc.InlineShapes.AddPicture(imgPath, ref linkToFile, ref saveWithDocument, ref myrange);
            if (width!=-1)
            {

                wordDoc.Application.ActiveDocument.InlineShapes[1].Width = height;//图片宽度 
            }
            if (height != -1)
            {

                wordDoc.Application.ActiveDocument.InlineShapes[1].Height = height;//图片高度 
            }

            Microsoft.Office.Interop.Word.Paragraph return_pragraph;
            object myrange2 = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
            return_pragraph = wordDoc.Content.Paragraphs.Add(ref myrange2);
            return_pragraph.Range.InsertParagraphAfter(); //插入一个空白行
        }

        public static void BookMarkReplace(Document wordDoc, string bookMark, string type, string value)
        {
            
            foreach (Bookmark bm in wordDoc.Bookmarks)
            {
                if (bm.Name == bookMark)
                {
                    Object missing = Missing.Value;
                    if (type == "IMG")
                    {
                        bm.Select();
                        //bm.Range.Text = "";//这句不能加加了下句就报对象已被移除,所以做图片书签的时候选空格来做就看不出来了
                        var img=bm.Range.InlineShapes.AddPicture(@value, ref missing, ref missing); //插入图片
                        img.Width = 600; //自动等比
                        //img.Height = 300;
                        

                    }
                    else if (type == "TABLE")
                    {
                        System.Data.DataTable table = Utils.JsonDataTableConvert.ToDataTable(value);//json转datatable

                        //http://zhidao.baidu.com/link?url=Zo7GtNDbA3cnqy-g2QM9cIEWxrw5Le6W0l_MsNnYnF_d6NrEufjkmjGyZj9AC2liuj8JSSKiw4nky6MHueexEFk99z8XXpOo2_eMct2MIB3
                        Table wtable = wordDoc.Tables.Add(wordDoc.Bookmarks.get_Item(bookMark).Range, table.Rows.Count + 1, table.Columns.Count); /*行+1是表格列头*/



                        System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
                        stopwatch.Start(); //  开始监视代码运行时间


                        wtable.set_Style("网格型");


                        int tableRowCount = table.Rows.Count;
                        int tableColumnCount = table.Columns.Count;
                        //表格列名
                        for (int i = 1; i <= tableColumnCount; i++)
                        {
                            wtable.Rows[1].Cells[i].Range.Font.Bold = 1;
                            wtable.Rows[1].Cells[i].Range.Font.Size=10;
                            wtable.Rows[1].Cells[i].Range.Text = table.Columns[i - 1].ColumnName;
                        }
                        //循环往表格里赋值
                        for (int i = 1; i <= tableRowCount; i++)
                        {
                            for (int j = 1; j <= tableColumnCount; j++)
                            {
                                wtable.Rows[i + 1].Cells[j].Range.Font.Bold = 0;
                                wtable.Rows[i + 1].Cells[j].Range.Font.Size = 10;
                                wtable.Rows[i + 1].Cells[j].Range.Text = table.Rows[i - 1][j - 1].ToString();
                            }
                        }

                        //  your code ....
                        stopwatch.Stop(); //  停止监视
                        TimeSpan timespan = stopwatch.Elapsed; //  获取当前实例测量得出的总时间
                        double hours = timespan.TotalHours; // 总小时
                        double minutes = timespan.TotalMinutes;  // 总分钟
                        double seconds = timespan.TotalSeconds;  //  总秒数
                        double milliseconds = timespan.TotalMilliseconds;  //  总毫秒数

                        Logger.InfoLog(tableRowCount+"行*"+tableColumnCount+"列,耗时:"+minutes+"分钟,折合:"+seconds+"秒.");

                    }
                    else
                    {//其他文字,日期等文字
                        bm.Select();//选中书签
                        bm.Range.Text = value + "\r\n";//替换文字
                    }

                    break;
                }
            }


        }

    }
}


调用:

 

DateTime dt = DateTime.Now;
            var basePath = Server.MapPath("~/Upload/");
            object savePathWord = basePath + "tem/" + dt.ToString("yyyy-MM-dd--HH-mm-ss-") + dt.Millisecond + "_" + fileName + ".docx";

            File.Copy(Server.MapPath("~/") + wordTemplatePath, savePathWord.ToString());

            Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
            appWord.ScreenUpdating = false;
            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
            object Visible = false;
            object ReadOnly = false;
            object missing = System.Reflection.Missing.Value;
            doc = appWord.Documents.Open(ref savePathWord, ref missing, ref ReadOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing);

            try
            {

                foreach (var item in ftvs)
                {//表单值写入word               

                    if (item.ControlType != "IMG" && item.ControlType != "WORD" && item.ControlType != "EXCEL" && item.ControlType != "TABLE")
                    {//文本 日期 等文字内容
                        if (item.Id == -1)
                        {//insert

                        }
                        else
                        {//update

                        }

                        <span style="color:#ff0000;">WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, item.Value);
</span>

                    }
                    else
                    {//附件已经在上传的时候插入了附件表和内容表,现在要把内容表的record_id外键改过来(默认为NULL)
                        if (item.ControlType == "TABLE")
                        {//表格
                            <span style="color:#ff0000;">WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, item.Value);</span>
                        }
                        else if (item.ControlType == "IMG")
                        {
                            //放在最后集中处理
                        }
                    }
                }

                #region 单独处理图片
                //*****单独处理图片

                //if (formTemplateValue_Ids != null)
                //{
                //    string[] ftvIds = formTemplateValue_Ids.Split(',');
                //    var imgs = dc.FormTemplateValues.Where(ee => ee.ControlType == "IMG" && ftvIds.Contains(ee.Id.ToString()));
                //    foreach (var item in imgs)
                //    {
                //        string imgPath =GetImgPath(item.Id);//Server.MapPath("~/")+item.PdfPath; //保存图片的时候也存在了服务器上
                //        WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, imgPath);
                //    }
                //}

                var imgs = dc.FormTemplateValues.Where(ee => ee.IsDeleted == false).Where(ee => ee.ControlType == "IMG" && ee.FormTemplateRecord_Id == recordId);
                foreach (var item in imgs)
                {
                    string imgPath = GetImgPath(item.Id);//Server.MapPath("~/")+item.PdfPath; //保存图片的时候也存在了服务器上
                    <span style="color:#ff0000;">WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, imgPath);</span>
                }
                #endregion



                appWord.ScreenUpdating = true;
                doc.Save();
                doc.Close(ref missing, ref missing, ref missing);
                //关闭wordApp组件对象 
                appWord.Quit(ref missing, ref missing, ref missing);


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

posted @   Ace001  阅读(812)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示