Asp.net或C#使用word模板生成替换后的Word和pdf文档-总结

本文详细介绍了在企业管理项目开发中如何利用模板文件和用户数据,通过编程方式生成指定格式的Word和PDF文档。主要内容包括在项目中引入必要的库,确保模板文件夹和临时文件夹的存在,并实现代码逻辑来读取模板、填充数据和导出文件。
在企业管理项目开发中,经常会有使用给定的模板文件,以及用户提交到数据里的数据,按照一定的格式,生成指定的word和pdf文档。
在这里进行一个总结:
注意:(1)要再项目中添加引用:
using System.Collections.Generic;
using System.IO;
using Microsoft.Office.Interop.Word;
(2)保证模板文件夹和文件临时文件夹的存在。
<img src="https://img-blog.youkuaiyun.com/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);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值