昨天做了下导入导出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. 错误:android.util.SuperNotCalledException

    android.util.SuperNotCalledException: Activity {…….YouTubePlayActivity} did not call through to supe ...

  2. Python 之 基础知识(四)

    一.公共方法(列表.元组.字典以及字符串) 1.内置函数 cmp函数取消可以用比较运算符来代替,但是字典是无序的,故而不可以用比较运算符比较. 2.切片(列表.元组.字符串适用) 3.运算符 列表中直 ...

  3. PythonOpencv-分类器—SVM,KNearest,RTrees,Boost,MLP

    原文链接:http://blog.csdn.net/gjy095/article/details/9243153 上一篇文章,不是很详细,这一篇解释的清晰些,请访问原始链接. Rtrees介绍!参考链 ...

  4. window窗口操作

    打开新窗口 window.open([url],[窗口名称],[参数字符串]) window.open("http://baidu.com","_balnk", ...

  5. php生成唯一识别码uuid

    /*生成唯一标志*标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxxxx-xxxxxxxxxx(8-4-4-4-12)*/ function uuid() { $chars = md ...

  6. ZBrush快捷键与鼠标操作

    ZBrush是一款3D图形绘制软件,功能十分强大,且比较复杂,除了菜单栏功能按钮,ZBrush还提供了一系列快捷键与鼠标操作,熟练掌握ZBrush快捷键与鼠标操作,可以帮助您大大节省图形创作时间.下面 ...

  7. JS去空格、截取页面url

    1.  去掉字符串前后所有空格: 代码如下: function Trim(str) { return str.replace(/(^\s*)|(\s*$)/g, ""); } 说明 ...

  8. DB2解决死锁

    方法一.查看db2diag.log文件 找到DeadLock or Lock timeout搜索 死锁或锁超时信息db2 force application(句柄ID)直接结束进程即可. 方法二.DB ...

  9. python类的内置attr属性

    class Foo: x=1 def __init__(self,y): self.y=y def __getattr__(self, item): print('----> from geta ...

  10. [luogu2272 ZJOI2007] 最大半连通子图 (tarjan缩点 拓扑排序 dp)

    传送门 题目描述 一个有向图G=(V,E)称为半连通的(Semi-Connected),如果满足:?u,v∈V,满足u→v或v→u,即对于图中任意两点u,v,存在一条u到v的有向路径或者从v到u的有向 ...