Asp.net或C#使用word模板生成替換後的Word和pdf文檔-總結

在企業管理項目開發中,經常會有使用給定的模板文件,以及用戶提交到數據裏的數據,按照一定的格式,生成指定的word和pdf文檔。
在這裏進行一個總結:
注意:(1)要再項目中添加引用:
using System.Collections.Generic;
using System.IO;
using Microsoft.Office.Interop.Word;
(2)保證模板文件夾和文件臨時文件夾的存在。
<img src="https://img-blog.csdn.net/20151110170122093?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
以下是頁面的代碼:(全)
    protected void Button1_Click(object sender, EventArgs e)
    {
        Dictionary<string, string> bookmarks = new Dictionary<string, string>();
        bookmarks.Add("proName", "項目名稱");
        bookmarks.Add("proNum", "項目編號");

        GenerateWord(MapPath("~/FileTemplate/testTemplate.docx"), MapPath("~/FileTemp/temp2.docx"), MapPath("~/FileTemp/temp.pdf"),
            bookmarks);

    }
    /// <summary>
    /// 根據word模板文件導出word/pdf文件
    /// </summary>
    /// <param name="templateFile">模板路徑</param>
    /// <param name="fileNameWord">導出文件名稱</param>
    /// <param name="fileNamePdf">pdf文件名稱</param>
    /// <param name="bookmarks">模板內書籤集合</param>

    public static void GenerateWord(string templateFile, string fileNameWord, string fileNamePdf, Dictionary<string, string> bookmarks)
    {
        Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
        File.Copy(templateFile, fileNameWord, true);
        Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
        object Obj_FileName = fileNameWord;
        object Visible = false;
        object ReadOnly = false;
        object missing = System.Reflection.Missing.Value;
        object IsSave = true;
        object FileName = fileNamePdf;
        object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF;
        object LockComments = false;
        object AddToRecentFiles = true;
        object ReadOnlyRecommended = false;
        object EmbedTrueTypeFonts = false;
        object SaveNativePictureFormat = true;
        object SaveFormsData = false;
        object SaveAsAOCELetter = false;
        object Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingSimplifiedChineseGB18030;
        object InsertLineBreaks = false;
        object AllowSubstitutions = false;
        object LineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;
        object AddBiDiMarks = false;

        try
        {
            doc = app.Documents.Open(ref Obj_FileName, 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);
            doc.Activate();

            foreach (string bookmarkName in bookmarks.Keys)
            {
                Replace(doc, bookmarkName, bookmarks[bookmarkName]);
            }

            doc.SaveAs(ref FileName, ref FileFormat, ref LockComments,
                    ref missing, ref AddToRecentFiles, ref missing,
                    ref ReadOnlyRecommended, ref EmbedTrueTypeFonts,
                    ref SaveNativePictureFormat, ref SaveFormsData,
                    ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks,
                    ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks);
            doc.Close(ref IsSave, ref missing, ref missing);
        }
        catch
        {
            doc.Close(ref IsSave, ref missing, ref missing);
        }

    }
    ///<summary>
    /// 在word 中查找一個字符串直接替換所需要的文本
    /// </summary>
    /// <param name="strOldText">原文本</param>
    /// <param name="strNewText">新文本</param>
    /// <returns></returns>
    public void Replace(Microsoft.Office.Interop.Word.Document doc, string strOldText, string strNewText)
    {
        doc.Content.Find.Text = strOldText;
        object FindText, ReplaceWith, Replace;// 
        object MissingValue = Type.Missing;
        FindText = strOldText;//要查找的文本
        ReplaceWith = strNewText;//替換文本

        Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
        /*wdReplaceAll - 替換找到的所有項。
         * wdReplaceNone - 不替換找到的任何項。
         * wdReplaceOne - 替換找到的第一項。
         * */
        doc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式設置
        doc.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);
    }

發佈了27 篇原創文章 · 獲贊 6 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章