C#操作word模板

摘要:
stringnewDocFileName=Guid.NewGuid().ToString()。替换(“-”、“”);stringstrServerPath=Server.MapPath(“”)+“\\Model.doc”;//模板路径strigstrSavePath=服务器。MapPath(“Doc”)+“”+newDocFileName+“.Doc”//保存为str的路径

  

 string newDocFileName = Guid.NewGuid().ToString().Replace("-", "");
        string strServerPath = Server.MapPath("") + "\\Model.doc";  //模板路径
        string strSavePath = Server.MapPath("Doc") + "\\" + newDocFileName + ".doc";  //另存为的路径
        strURL = strServerPath;

        List<string> findText = new List<string>();
        List<string> replaceText = new List<string>();

        findText.Add("{NAME}");
        findText.Add("{AGE}");
        findText.Add("{SEX}");

        replaceText.Add("姓名");
        replaceText.Add("24岁");
        replaceText.Add("男");
        newDocFileName = "Doc/7c37c538b92749eeaf55efab579f2c3e.doc";
        ReplaceWordDocAndSave(copyWordDoc(strServerPath), strSavePath, findText, replaceText);

    /// <summary>
    /// 从源DOC文档复制内容返回一个Document类
    /// </summary>
    /// <param name="sorceDocPath">源DOC文档路径</param>
    /// <returns>Document</returns>
    protected Document copyWordDoc(object sorceDocPath)
    {
        object objDocType = WdDocumentType.wdTypeDocument;
        object type = WdBreakType.wdSectionBreakContinuous;

        //Word应用程序变量   
        Application wordApp;
        //Word文档变量
        Document newWordDoc;

        object readOnly = false;
        object isVisible = false;

        //初始化
        //由于使用的是COM库,因此有许多变量需要用Missing.Value代替
        wordApp = new ApplicationClass();

        Object Nothing = System.Reflection.Missing.Value;

        newWordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

        Document openWord;
        openWord = wordApp.Documents.Open(ref sorceDocPath, ref Nothing, ref readOnly, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref isVisible, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
        openWord.Select();
        openWord.Sections[1].Range.Copy();

        object start = 0;
        Range newRang = newWordDoc.Range(ref start, ref start);

        //插入换行符   
        //newWordDoc.Sections[1].Range.InsertBreak(ref type);
        newWordDoc.Sections[1].Range.PasteAndFormat(WdRecoveryType.wdPasteDefault);
        openWord.Close(ref Nothing, ref Nothing, ref Nothing);
        return newWordDoc;
    }
    /// <summary>
    /// 替换指定Document的内容,并保存到指定的路径
    /// </summary>
    /// <param name="docObject">Document</param>
    /// <param name="savePath">保存到指定的路径</param>
    protected void ReplaceWordDocAndSave(Document docObject, object savePath, List<string> findText, List<string> replaceText)
    {
        object format = WdSaveFormat.wdFormatDocument;
        object readOnly = false;
        object isVisible = false;

        //string strOldText = "{WORD}";
        //string strNewText = "替换后的文本";

        List<string> IListOldStr = findText;
        List<string> IListNewStr = replaceText;

        string[] newStr = IListNewStr.ToArray();
        int i = 0;

        Object Nothing = System.Reflection.Missing.Value;

        Microsoft.Office.Interop.Word.Application wordApp = new ApplicationClass();
        Microsoft.Office.Interop.Word.Document oDoc = docObject;

        object FindText, ReplaceWith, Replace;
        object MissingValue = Type.Missing;

        foreach (string str in IListOldStr)
        {
            oDoc.Content.Find.Text = str;
            //要查找的文本
            FindText = str;
            //替换文本
            //ReplaceWith = strNewText;
            ReplaceWith = newStr[i];
            i++;

            //wdReplaceAll - 替换找到的所有项。
            //wdReplaceNone - 不替换找到的任何项。
            //wdReplaceOne - 替换找到的第一项。
            Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;

            //移除Find的搜索文本和段落格式设置
            oDoc.Content.Find.ClearFormatting();

            if (oDoc.Content.Find.Execute(ref FindText, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref ReplaceWith, ref Replace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue))
            {
                Response.Write("替换成功!");
                Response.Write("<br>");
            }
            else
            {
                Response.Write("没有相关要替换的:(" + str + ")字符");
                Response.Write("<br>");
            }
        }

        oDoc.SaveAs(ref savePath, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

        //关闭wordDoc文档对象    
        oDoc.Close(ref Nothing, ref Nothing, ref Nothing);
        //关闭wordApp组件对象    
        wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
    }

免责声明:文章转载自《C#操作word模板》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Nmap目录扫描和漏洞扫描(9.27 第十三天)用windbg分析一个dead lock的问题下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

算法--字符串移位问题

转载请标明出处http://www.cnblogs.com/haozhengfei/p/d06ff7b10334cd17ec014764b96790ca.html 字符串移位问题 字符串移位练习题 第7节 字符串移位练习题 对于一个字符串,请设计一个算法,将字符串的长度为len的前缀平移到字符串的最后。 给定一个字符串A和它的长度,同时给定le...

带中文的字符串截取

最近在页面展示的时候遇到这样的场景,文字有可能超长,却又不允许换行。 当然,可以用高超的css来搞定。但如果你想要让多余的文字用“...”来代替,并且要兼容很多浏览器,这种时候用css也会很头疼吧。 1.C#对中文字符串的截取 与英文字符相比,我们把中文字符按两个占位来计算,对于带中文的字符串截取,要面临两个问题: 1.无法截取半个中文字符; 2.对于除...

【216】◀▶ IDL 字符串操作说明 (黑底)

参考:String Processing Routines —— 字符串处理函数 参考:IDL_String Methods 01   STRING 返回字符串。 02   STRCMP 比较字符串,一样返回1,不一样返回0,默认大小写敏感。 03   STRMATCH 字符串进行比较,一致返回1,不一致返回0。 04   STRCOMP...

C# FreeSpire.Doc 操作word文档

C# FreeSpire.Doc 免费的word文档类库 环境准备 Nuget安装 FreeSpire.Doc 引用 using Spire.Doc; using Spire.Doc.Documents; using System.IO; Html转换为word文档 static void GetHtmlDocument() {...

ASP.NET Core SignalR (七):考虑设计向后兼容的SignalR API

此为系列文章,对MSDN ASP.NET Core SignalR 的官方文档进行系统学习与翻译。其中或许会添加本人对 ASP.NET Core 的浅显理解。 使用自定义参数对象来确保向后兼容         向SignalR 中心 方法添加参数(要么是服务端方法,要么是客户端方法)是一个重大的变化。这就意味着老的 服务端/客户端在不带有预期个数的参数进行...

FastJSON反序列化学习

反序列化漏洞例子 0x00、fastJSON练习 参考上面的链接,写一个类,并用fastJSON序列化。查阅API,fastJSON的序列化函数有: public abstract class JSON { // 将Java对象序列化为JSON字符串,支持各种各种Java基本类型和JavaBean public static String...