本博客实现通过模板动态生成word文档。
- C#
- Visual Studio 2013
- Microsoft.Office.Interop.Word.dll –>需要添加该引用,可以在网上下载
关键代码如下:
public void ExportWord()
{
//取得模板路径
string wordTemplatePath = @"C:\XXXXX\模板.doc";
//导出文件名称
fileName = "我的word" + System.DateTime.Now.ToString("yyyMMddHHmmss") + ".doc";
//导出文件路径
string outPutFilePath = @"C:\XXXXX\" + fileName;
//创建word对象
object missing = System.Reflection.Missing.Value;
object readOnly = false;
Word.Application app = new Word.Application();
Word.Document doc = null;
File.Copy(wordTemplatePath, outPutFilePath, true);//true 相同文件名时,覆盖
//打开doc
object tempword = (object)wordTemplatePath;
object output = (object)outPutFilePath;
doc = app.Documents.Open(ref tempword, ref missing, ref readOnly, 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);
doc.Activate();
//插入4行4列表格
WdLineStyle OutStyle = WdLineStyle.wdLineStyleThickThinLargeGap;
WdLineStyle InStyle = WdLineStyle.wdLineStyleSingle;
AddSimpleTable(app, d