1. 程式人生 > >Asponse.Words進行Word替換

Asponse.Words進行Word替換

main style 光標 spa center foreach 獲取 console 指定節點

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using Aspose.Words;
using Aspose.Words.Drawing;
using System.IO;


namespace ASPONSE_Words
{
    public class Program
    {
        static void
Main(string[] args) { Console.WriteLine("開始進行操作"); DataTable dt = new DataTable(); dt.Columns.Add("title", typeof(string)); dt.Columns.Add("xm", typeof(string)); dt.Columns.Add("xb", typeof(string)); dt.Columns.Add(
"mz", typeof(string)); dt.Columns.Add("nl", typeof(string)); dt.Columns.Add("Photo1", typeof(string)); dt.Columns.Add("Photo2", typeof(string)); dt.Columns.Add("Photo3", typeof(string)); dt.Columns.Add("Photo4", typeof(string)); DataRow dr
= dt.NewRow(); dr["title"] = "測試"; dr["xm"] = "華哥"; dr["xb"] = "男神"; dr["mz"] = "漢族"; dr["nl"] = "18"; dr["Photo1"] = "../File/1.jpg"; dr["Photo2"] = "../File/2.jpg"; dr["Photo3"] = "../File/3.jpg"; dr["Photo4"] = "../File/4.jpg"; dt.Rows.Add(dr); var fileUrl = "../File/test11.doc"; try { Print(fileUrl, dt); Console.WriteLine("替換成功"); } catch (Exception) { Console.WriteLine("替換失敗"); } Console.ReadKey(); } public static void Print(string fileurl, DataTable dtInfo) { Document doc = new Document(fileurl); if (dtInfo != null && dtInfo.Rows.Count > 0) { var dr = dtInfo.Rows[0]; foreach (DataColumn dc in dtInfo.Columns) { var nValue = dr[dc.ColumnName] + ""; try { if (dc.ColumnName.Contains("Photo")) { if (File.Exists(nValue)) { Regex reg = new Regex("#" + dc.ColumnName + "#"); doc.Range.Replace(reg, new ReplaceImage2(nValue), false); } } else doc.Range.Replace("$"+dc.ColumnName+"$", nValue, false, false); } catch (Exception) { } } } doc.Save("ceshi.doc"); } } public class ReplaceImage1 : IReplacingCallback { public string imageUrl; public ReplaceImage1(string url) { this.imageUrl = url; } public ReplaceAction Replacing(ReplacingArgs e) { //獲取當前節點 var node = e.MatchNode; //獲取當前文檔 Document doc = node.Document as Document; DocumentBuilder builder = new DocumentBuilder(doc); //將光標移動到指定節點 builder.MoveTo(node); //插入圖片 builder.InsertImage(imageUrl); return ReplaceAction.Replace; } } public class ReplaceImage2 : IReplacingCallback { public string imageUrl; public ReplaceImage2(string url) { this.imageUrl = url; } public ReplaceAction Replacing(ReplacingArgs e) { //獲取當前節點 if (!string.IsNullOrEmpty(imageUrl)) { var node = e.MatchNode; Document doc = node.Document as Document; DocumentBuilder builder = new DocumentBuilder(doc); builder.MoveTo(node); Shape shape = new Shape(doc, ShapeType.Image); shape.ImageData.SetImage(imageUrl); shape.Top = 0; shape.Width = 80; shape.Height = 100; shape.HorizontalAlignment = HorizontalAlignment.Center; CompositeNode node1 = shape.ParentNode; builder.InsertNode(shape); } return ReplaceAction.Replace; } } }

模板:

技術分享

效果圖:

技術分享

Asponse.Words進行Word替換