昨天做了下导入导出Excel文件,今天研究了下导出Word文件。 从网上找了半天才找到了一个能导出到指定模板的,在这里总结下。

导出模板原理就是利用的替换占位符。

我这里先建立好了一个模板,

接下来写代码进行导出,

前端就一段AJAX调用,这里我就不写了,直接上后端代码,看下面:

     /// <summary>
/// 导出Word文件
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult LeadWord()
{
#region 动态创建DataTable数据
DataTable tblDatas = new DataTable("Datas");
DataColumn dc = null;
//赋值给dc,是便于对每一个datacolumn的操作
dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32"));
dc.AutoIncrement = true;//自动增加
dc.AutoIncrementSeed = ;//起始为1
dc.AutoIncrementStep = ;//步长为1
dc.AllowDBNull = false;//
dc = tblDatas.Columns.Add("name", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("sex", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("age", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("str1", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("str2", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("str3", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("str4", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("str5", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("str6", Type.GetType("System.String"));
dc = tblDatas.Columns.Add("remark", Type.GetType("System.String"));
DataRow newRow;
newRow = tblDatas.NewRow();
newRow["name"] = "张三";
newRow["sex"] = "男";
newRow["age"] = "";
newRow["str1"] = "字符串1";
newRow["str2"] = "字符串2";
newRow["str3"] = "字符串3";
newRow["str4"] = "字符串4";
newRow["str5"] = "字符串5";
newRow["str6"] = "字符串6";
newRow["remark"] = "备注一下";
tblDatas.Rows.Add(newRow);
#endregion
#region word要替换的表达式和表格字段的对应关系
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("$name$", "name");
dic.Add("$sex$", "sex");
dic.Add("$age$", "age");
dic.Add("$str1$", "str1");
dic.Add("$str2$", "str2");
dic.Add("$str3$", "str3");
dic.Add("$str4$", "str4");
dic.Add("$str5$", "str5");
dic.Add("$str6$", "str6");
dic.Add("$remark$", "remark");
#endregion
string tempFile = "~/Content/Word/temp.doc";
string saveFile = "~/Content/Word/1.doc";
WordUtility w = new WordUtility(tempFile, saveFile);
w.GenerateWord(tblDatas, dic, null);
return Content("ok");
}

Helper Class(WordUtility.cs)

using System;
using System.Collections.Generic;
using System.Data;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
using System.Windows.Forms;
using System.Runtime.Remoting.Contexts; namespace Headfree.DefUI
{
/// <summary>
/// 使用替换模板进行到处word文件
/// </summary>
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)
{
tempFile=System.Web.HttpContext.Current.Server.MapPath(tempFile);
saveFile = System.Web.HttpContext.Current.Server.MapPath(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()))
{ 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 > )
isGenerate = ReplaceAllRang(simpleExpPairValue); // 表格有重复
if (dt != null && dt.Rows.Count > && expPairColumn != null && expPairColumn.Count > )
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)
{
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[]; tb.Range.Copy(); Dictionary<string, object> dc = new Dictionary<string, object>();
for (int i = ; i < tableNums; i++)
{
dc.Clear(); if (i == )
{
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[], 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[], dc);
} return true;
}
catch (Exception ex)
{
DisposeWord();
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(); 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)
{
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进程
}
}
}

好了,代码就这么多,来看下导出效果吧:

ZJ。。。

C#将内容导出到Word到指定模板的更多相关文章

  1. javascript下用ActiveXObject控件替换word书签,将内容导出到word后打印第1/2页

    由于时间比较紧,没多的时候去学习研究上述工具包,现在用javascript操作ActiveXObject控件,用替换word模板中的书签方式解决. 最近有需求将数据导出到word里,然后编辑打印. 想 ...

  2. 内容导出成word

    private void 导出word(string 内容) { string tit = "<html xmlns:v=\"urn:schemas-microsoft-co ...

  3. PHP获取网址详情页的内容导出到WORD文件

    亲自测试效果一般, css的样式文件获取不到 如果没有特殊的样式  或者是内容里面包括样式的  直接输出有样式的内容 然后导出  这样还是可以的 class word { function start ...

  4. PowerDesigner导出word,PowerDesigner把表导出到word,PDM导出word文档

    PowerDesigner导出word,PowerDesigner把表导出到word,PDM导出word文档 >>>>>>>>>>>& ...

  5. java导出生成word(类似简历导出)

    参考帖子: http://www.cnblogs.com/lcngu/p/5247179.html http://www.cnblogs.com/splvxh/archive/2013/03/15/2 ...

  6. java导出生成word

    最近做的项目,需要将一些信息导出到word中.在网上找了好多解决方案,现在将这几天的总结分享一下. 目前来看,java导出word大致有6种解决方案: 1:Jacob是Java-COM Bridge的 ...

  7. 导出到word

    导出到excel功能会常做,但是导出到word功能很少做,项目遇到,在这里做一下标记. 导出到excel比较容易,excel都有固定格式也模板,但是word需要自己写模板,这里用了freemarker ...

  8. PowerDesigner逆向操作(从mysql5.0生成数据库的物理模型),把Comment写到name中,pdm文件导出为word

    PowerDesigner逆向操作(从mysql5.0生成数据库的物理模型) 环境:powderdesigner12.5:mysql5.0步骤:1. 为指定的数据库配置mysql的ODBC数据源先下载 ...

  9. (转)WEB页面导出为Word文档后分页&横向打印的方法

    <html>    <HEAD>        <title>WEB页面导出为Word文档后分页&横向打印的方法 </title>    < ...

随机推荐

  1. hdu2853 Assignment 完美匹配 多校联赛的好题

    PS:好题.不看题解绝对AC不了. 题解来源: http://blog.csdn.net/niushuai666/article/details/7176290 http://www.cnblogs. ...

  2. 目标跟踪ObjectT综述介绍

    此文也很详细:http://blog.csdn.net/maochongsandai110/article/details/11530045 原文链接:http://blog.csdn.net/pp5 ...

  3. (转) RabbitMQ学习之工作队列(java)

    http://blog.csdn.net/zhu_tianwei/article/details/40887717 参考:http://blog.csdn.NET/lmj623565791/artic ...

  4. apiCloud组件:swiper

    一.apicloud中基于swiper封装了一个模块供调用.就是swiper.js 页面引入js就行 <script type="text/javascript" src=& ...

  5. Python3与2的故事一

    print函数:(Python3中print为一个函数,必须用括号括起来:Python2中print为class) Python 2 的 print 声明已经被 print() 函数取代了,这意味着我 ...

  6. 安装oracle执行runInstaller文件时报错:“……/install/.oui:Permission denied”

    一:问题描述 二:出错原因 将windows下未解压的Oracle安装软件上传到了linux服务器,导致有三个文件的执行权限丢失. 三:解决方法 为其赋予相应权限即可. 1: [root@MyPc ~ ...

  7. ListUtil常用操作

    /** * 获取列表总页数 */ public static <T> int getListPages(List<T> list,int pageNum,int pageSiz ...

  8. Codeforces Round #471 (Div. 2)A. Feed the cat

    After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another ...

  9. parted分区流程操作

    parted不同于fdisk(<2T)它比fdiskf更加灵活,fdisk需保持后才能生效,而parted是分区后直接生效! 磁盘分区步骤: 1.parted /dev/sdb #进入磁盘分区 ...

  10. JavaScript原生值与JSON的转换

    ---------------------------------- ---------------------------- stringify方法的另外两种参数: ---------------- ...