C# 根据Word模版生成Word文件
指定的word模版
2,生成word类
添加com Microsoft word 11.0 Object Library 引用
using System; using System.Collections.Generic; using System.Data; using System.Windows.Forms; using Word = Microsoft.Office.Interop.Word; using System.IO; namespace Headfree.DefUI { public class WordUtility { private object tempFile = null ; private object saveFile = null ; private static Word._Document wDoc = null ; //word文档 private static Word._Application wApp = null ; //word进程 private object missing = System.Reflection.Missing.Value; public WordUtility( string tempFile, string saveFile) { this .tempFile = Path.Combine(Application.StartupPath, @tempFile); this .saveFile = Path.Combine(Application.StartupPath, @saveFile); } /// <summary> /// 模版包含头部信息和表格,表格重复使用 /// </summary> /// <param name="dt">重复表格的数据</param> /// <param name="expPairColumn">word中要替换的表达式和表格字段的对应关系</param> /// <param name="simpleExpPairValue">简单的非重复型数据</param> public bool GenerateWord(DataTable dt, Dictionary< string , string > expPairColumn, Dictionary< string , string > simpleExpPairValue) { if (!File.Exists(tempFile.ToString())) { MessageBox.Show( string .Format( "{0}模版文件不存在,请先设置模版文件。" , tempFile.ToString())); return false ; } try { wApp = new Word.Application(); wApp.Visible = false ; wDoc = wApp.Documents.Add( ref tempFile, ref missing, ref missing, ref missing); wDoc.Activate(); // 当前文档置前 bool isGenerate = false ; if (simpleExpPairValue != null && simpleExpPairValue.Count > 0) isGenerate = ReplaceAllRang(simpleExpPairValue); // 表格有重复 if (dt != null && dt.Rows.Count > 0 && expPairColumn != null && expPairColumn.Count > 0) isGenerate = GenerateTable(dt, expPairColumn); if (isGenerate) wDoc.SaveAs( ref saveFile, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); DisposeWord(); return true ; } catch (Exception ex) { MessageBox.Show( "生成失败" + ex.Message); return false ; } } /// <summary> /// 单个替换 模版没有重复使用的表格 /// </summary> /// <param name="dc">要替换的</param> public bool GenerateWord(Dictionary< string , string > dc) { return GenerateWord( null , null , dc); } private bool GenerateTable(DataTable dt, Dictionary< string , string > expPairColumn) { try { int tableNums = dt.Rows.Count; Word.Table tb = wDoc.Tables[1]; tb.Range.Copy(); Dictionary< string , object > dc = new Dictionary< string , object >(); for ( int i = 0; i < tableNums; i++) { dc.Clear(); if (i == 0) { foreach ( string key in expPairColumn.Keys) { string column = expPairColumn[key]; object value = null ; value = dt.Rows[i][column]; dc.Add(key, value); } ReplaceTableRang(wDoc.Tables[1], dc); continue ; } wDoc.Paragraphs.Last.Range.Paste(); foreach ( string key in expPairColumn.Keys) { string column = expPairColumn[key]; object value = null ; value = dt.Rows[i][column]; dc.Add(key, value); } ReplaceTableRang(wDoc.Tables[1], dc); } return true ; } catch (Exception ex) { DisposeWord(); MessageBox.Show( "生成模版里的表格失败。" + ex.Message); return false ; } } private bool ReplaceTableRang(Word.Table table, Dictionary< string , object > dc) { try { object replaceArea = Word.WdReplace.wdReplaceAll; foreach ( string item in dc.Keys) { object replaceKey = item; object replaceValue = dc[item]; table.Range.Find.Execute( ref replaceKey, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceValue, ref replaceArea, ref missing, ref missing, ref missing, ref missing); } return true ; } catch (Exception ex) { DisposeWord(); MessageBox.Show( string .Format( "{0}模版中没有找到指定的要替换的表达式。{1}" , tempFile, ex.Message)); return false ; } } private bool ReplaceAllRang(Dictionary< string , string > dc) { try { object replaceArea = Word.WdReplace.wdReplaceAll; foreach ( string item in dc.Keys) { object replaceKey = item; object replaceValue = dc[item]; wApp.Selection.Find.Execute( ref replaceKey, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceValue, ref replaceArea, ref missing, ref missing, ref missing, ref missing); } return true ; } catch (Exception ex) { MessageBox.Show( string .Format( "{0}模版中没有找到指定的要替换的表达式。{1}" , tempFile, ex.Message)); return false ; } } private void DisposeWord() { object saveOption = Word.WdSaveOptions.wdSaveChanges; wDoc.Close( ref saveOption, ref missing, ref missing); saveOption = Word.WdSaveOptions.wdDoNotSaveChanges; wApp.Quit( ref saveOption, ref missing, ref missing); //关闭Word进程 } } } |
3,效果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示