C#通過模板導出Word的兩種方法(超簡單)

方法一:使用Office的組件

使用該方法必須要安裝Office

1、製作Word模板

Word模板
在需要填充內容的地方增加標識符號,方便之後替換使用,例如 [項目名稱],其中[]符號和中間的文字可根據個人情況進行修改。

到此模板已經制作完成,是不是很簡單。

2、操作Word

2.1 引用Microsoft.Office.Interop.Word.dll

添加命名空間

using Word = Microsoft.Office.Interop.Word;

2.2 編碼開始

string mubanFile = "模板.docx";
string templatePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, mubanFile);
Dictionary<string, string> bookmarks = new Dictionary<string, string>();
var item=xxx;//數據源
//將數據與Word模板中的標籤對應
bookmarks.Add("[姓名]", item.UserName);
bookmarks.Add("[性別]", item.Sex);
bookmarks.Add("[出生年月]", item.BirthDay);
bookmarks.Add("[民族]", item.Ethnic);
bookmarks.Add("[文化程度]", item.EducationalLevel);
bookmarks.Add("[詳細地址]", item.Address);
bookmarks.Add("[電話]", item.Phone);  
string wordpath = outputPath +  "xx.docx";//導出word地址
string pdfpath = outputPath +  "xx.pdf";//導出pdf地址
GenerateWord(templatePath, wordpath, pdfpath, 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)
            {                
                string newstr;
                string newStrs;

                replace(doc, bookmarkName, bookmarks[bookmarkName]);//替換內容
                }
                //replace(doc, "hello", "shalv");
                //此處存儲時,參數可選填,如需另外生成pdf,加入一個參數ref FileName,
                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 (Exception ex)
            {
                LogHelper.WriteLog(ex.ToString());
                doc.Close(ref IsSave, ref missing, ref missing);
            }

        }
        ///<summary>
        /// 在word 中查找一個字符串直接替換所需要的文本
        /// </summary>
        /// <param name="strOldText">原文本</param>
        /// <param name="strNewText">新文本</param>
        /// <returns></returns>
        public static 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);
        }

好了,到這就完成了。

不過有個小問題,這種替換的方式,當要替換的字符串超過一定的長度,就會提示“字符串參量過長”,搜索發現,替換的最大長度爲255字符

下面是解決方法
在替換前判斷替換內容長度是否超過255,如果超長就分段替換,代碼如下

foreach (string bookmarkName in bookmarks.Keys)
{
      int len = bookmarks[bookmarkName].Length;
      int cnt = len / 255;
      string newstr;
      string newStrs;

      if (bookmarks[bookmarkName].Length < 255)
      {
              replace(doc, bookmarkName, bookmarks[bookmarkName]);//替換內容
      }
      else
      {
             for (int i = 0; i <= cnt; i++)
             {
                    if (i != cnt)
                         newstr = bookmarks[bookmarkName].ToString().Substring(i * 255, 255) + bookmarkName;  //新的替換字符串
                    else
                         newstr = bookmarks[bookmarkName].ToString().Substring(i * 255, len - i * 255);    //最後一段需要替換的文字
                        newStrs = newstr;
                        replace(doc, bookmarkName, newStrs);//替換內容
              }
       }
}

第一種方法搞定!!!

方法二:使用Aspose.Words

這種方法不用安裝office。

1、製作模板

在需要替換的地方插入域,插入-》文檔部件-》域-》選擇MergeField,在域名處添加內容。
WPS的步驟爲 插入-》選擇文檔部件-》選擇域-》選擇郵件合併
在這裏插入圖片描述
添加完成後的效果如下:
在這裏插入圖片描述

2、上代碼

2.1 添加引用

using Aspose.Words;

2.1 建立對應關係

string[] fieldNames = new string[] { "姓名", "性別", "出生年月", "民族", "文化程度", "詳細地址", "電話" };
object[] fieldValues = new object[] { item.Name, item.Sex, item.BirthDay, item.Ethnic, item.EducationalLevel, item.Address, item.Phone};

string mubanFile = "模板1.docx";
string templatePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, mubanFile);
string wordpath = outputPath +  "xx.docx";//導出word地址

AsposeWordHelper helper = new AsposeWordHelper();
helper.OpenTempelte(templatePath); //打開模板文件
helper.Executefield(fieldNames, fieldValues);//域賦值
helper.SaveDoc(wordpath); //文件保存

下面是word文檔操作輔助類AsposeWordHelper.cs的內容

/// <summary>
    /// word文檔操作輔助類
    /// </summary>
    public class AsposeWordHelper
    {
        /// <summary>
        /// Word
        /// </summary>
        private Document wordDoc;

        /// <summary>
        /// 基於模版新建Word文件
        /// </summary>
        /// <param name="path">模板路徑</param>
        public void OpenTempelte(string path)
        {
            
            wordDoc = new Document(path);
    }

    /// <summary>
    /// 書籤賦值用法
    /// </summary>
    /// <param name="LabelId">書籤名</param>
    /// <param name="Content">內容</param>
    public void WriteBookMark(string LabelId, string Content)
    {
        if (wordDoc.Range.Bookmarks[LabelId] != null)
        {
            wordDoc.Range.Bookmarks[LabelId].Text = Content;
        }
    }

    /// <summary>
    /// 列表賦值用法
    /// </summary>
    /// <param name="dt"></param>
    public void WriteTable(DataTable dt)
    {
        wordDoc.MailMerge.ExecuteWithRegions(dt);
    }

    /// <summary>
    /// 文本域賦值用法
    /// </summary>
    /// <param name="fieldNames">key</param>
    /// <param name="fieldValues">value</param>
    public void Executefield(string[] fieldNames, object[] fieldValues)
    {
        wordDoc.MailMerge.Execute(fieldNames, fieldValues);
    }

    /// <summary>
    /// Pdf文件保存
    /// </summary>
    /// <param name="filename">文件路徑+文件名</param>
    public void SavePdf(string filename)
    {
        wordDoc.Save(filename, SaveFormat.Pdf);
    }

    /// <summary>
    /// Doc文件保存
    /// </summary>
    /// <param name="filename">文件路徑+文件名</param>
    public void SaveDoc(string filename)
    {
        wordDoc.Save(filename, SaveFormat.Doc);
    }

    /// <summary>
    /// 不可編輯受保護,需輸入密碼
    /// </summary>
    /// <param name="pwd">密碼</param>
    public void NoEdit(string pwd)
    {
        wordDoc.Protect(ProtectionType.ReadOnly, pwd);
    }

    /// <summary>
    /// 只讀
    /// </summary>
    public void ReadOnly()
    {
        wordDoc.Protect(ProtectionType.ReadOnly);
    }

    /// <summary>
    /// 通過流導出word文件
    /// </summary>
    /// <param name="stream">流</param>
    /// <param name="fileName">文件名</param>
    public static HttpResponseMessage ExportWord(Stream stream, string fileName)
    {
        var file = stream;
        fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(file);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = fileName + ".doc";
        return result;
    }

    /// <summary>
    /// 通過流導出pdf文件
    /// </summary>
    /// <param name="stream">流</param>
    /// <param name="fileName">文件名</param>
    public static HttpResponseMessage ExportPdf(Stream stream, string fileName)
    {
        var file = stream;
        fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new StreamContent(file);
        result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
        result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";
        return result;
    }

這種方法雖然不用安裝office,但是導出的文檔有AsposeWord的水印和頁眉,不過可以手動去掉。

大家有沒有其他的方法,歡迎討論。

如有錯誤,還請批評指正!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章