C# Aspose.Words 數據寫入到 Word


一、通過“域”寫入數據

在Word中,打開【插入】選項卡——【文檔部件】——【域】,在【域】的功能對話框中,可以看到有全部、編號、等式和公式等多種類別,通過選擇這些類別,可以使用域來進行自動更新的相關功能。包括公式計算、變化的時間日期、郵件合並等。

除了利用上述步驟插入域外,也可以按Ctrl+F9手工輸入域。域實際上是Word中的代碼,按Shift+F9可以在代碼與計算結果之間進行切換。此處不理解也沒關系,看下面例子就可以了。

 “《》”並不是自己手動打出來的,要通過文本域構建

插入文本域。(插入--->文檔部件--->域---->選擇MergeFileID--->填寫域名---->點擊保存)

 按Alt + F9 是這個樣子的

這個“域”可以通過我們后台代碼動態的顯示我們需要的值,比如說《Name》 想要變成 Name:Ramon ,Title:《Title》變成 Ramon Title

二、代碼實現

1.在實現的同時我們也需要准備好Aspose.Words.dll 破解版  可以上網找....

2.如果不是破解版他會有水印和自動生成的表頭和底部信息(商用還是用正版吧)

添加一個AsposeWordHelper幫助類

using Aspose.Words;
using Aspose.Words.Drawing;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;

namespace WordHelper
{
    /// <summary>
    /// word文檔操作輔助類
    /// </summary>
    public class AsposeWordHelper
    {
        /// <summary>
        /// Word
        /// </summary>
        private Document _doc;
        private string _tempPath;
        private SaveFormat _saveFormat;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tempPath">模板地址</param>
        /// <param name="saveFormat">轉換后的類型</param>
        public AsposeWordHelper(string tempPath, SaveFormat saveFormat = SaveFormat.Doc)
        {
            this._tempPath = tempPath;
            this._saveFormat = saveFormat;

        }

        /// <summary>
        /// 文本域處理泛型集合賦值
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="entity"></param>
        public void Execute<TEntity>(TEntity entity)
        {
            var type = entity.GetType();
            var properties = type.GetProperties();
            List<string> names = new List<string>();
            List<string> values = new List<string>();
            foreach (var item in properties)
            {
                names.Add(item.Name);
                values.Add(item.GetValue(entity, null).ToString());
            }
            _doc.MailMerge.Execute(names.ToArray(), values.ToArray());
        }

        /// <summary>
        /// 文本域處理鍵值對賦值
        /// </summary>
        /// <param name="entity"></param>
        public void Execute(Dictionary<string, string> entity)
        {
            List<string> names = new List<string>();
            List<string> values = new List<string>();
            foreach (var item in entity)
            {
                names.Add(item.Key);
                values.Add(item.Value);
            }
            _doc.MailMerge.Execute(names.ToArray(), values.ToArray());
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="filePath"></param>
        public void Save(string filePath)
        {
            _doc.Save(filePath, _saveFormat);
        }

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

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

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

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

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

        /// <summary>
        /// 添加圖片
        /// </summary>
        /// <param name="filename">文件路徑+文件名</param>
        /// <param name="field">文本域名</param>
        /// <param name="width">寬</param>
        /// <param name="height">高</param>
        public void AddImage(string filename, string field, double width = 70, double height = 70)
        {
            DocumentBuilder builder = new DocumentBuilder(_doc);
            Shape shape = new Shape(_doc, ShapeType.Image);
            shape.ImageData.SetImage(filename);
            shape.Width = width;//設置寬和高
            shape.Height = height;
            shape.WrapType = WrapType.None;
            shape.BehindText = true;
            builder.MoveToMergeField(field);
            builder.InsertNode(shape);
        }

        /// <summary>
        /// 通過流導出word文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        public HttpResponseMessage ExportWord(string fileName)
        {
            var stream = new MemoryStream();
            _doc.Save(stream, SaveFormat.Doc);
            fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(stream);
            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="fileName">文件名</param>
        public HttpResponseMessage ExportPdf(string fileName)
        {
            var stream = new MemoryStream();
            _doc.Save(stream, SaveFormat.Doc);
            fileName += DateTime.Now.ToString("yyyyMMddHHmmss");
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new StreamContent(stream);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = fileName + ".pdf";
            return result;
        }

    }
}

調用

using Aspose.Words;
using Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordHelper;

namespace WordTest.App
{
    class Program
    {
        private static readonly AsposeWordHelper _AsposeWordHelper;
        static Program() {
            _AsposeWordHelper = new AsposeWordHelper(@"C:\Users\NING MEI\Desktop\學習\test.docx");
        }
        static void Main(string[] args)
        {
            //鍵值對
            _AsposeWordHelper.OpenTempelte();  //打開定義好的模板
            _AsposeWordHelper.Execute(new Dictionary<string, string>{
                { "Name","Ramon"},
                { "Title","Ramon Title"},
            }); //替換域 賦值
            _AsposeWordHelper.ReadOnly();// 可以設為只讀
            _AsposeWordHelper.Save(@"C:\Users\NING MEI\Desktop\學習\1.doc");//保存到哪個路徑


            //泛型
            _AsposeWordHelper.OpenTempelte(); //打開定義好的模板
            _AsposeWordHelper.Execute(new ContractModel() { 
                Name = "Ramon",
                Title = "RamonTitle"
            
            }); //替換域 賦值
            _AsposeWordHelper.ReadOnly();// 可以設為只讀
            _AsposeWordHelper.Save(@"C:\Users\NING MEI\Desktop\學習\2.doc");//保存到哪個路徑
        }
    }
}

效果

 

 代碼只是隨便的寫了下還有很多可以擴展的地方的,小編就懶得擴展了,這只是一個demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM