1.第一步,准备word模版

2.第二步,将word模版保存成word2003xml格式。打开word文档,点击另存为,将文件保存为word 2003 XML文档。
3.第三步,以记事本的方式打开xml文件,清理头部信息。
删除<?mso-application progid="Word.Document"?>
4.第四步,记录xml命名空间
在IE中打开xml文件,记录下命名空间
http://schemas.microsoft.com/office/word/2003/wordml
http://schemas.microsoft.com/office/word/2003/auxHint
5.第五步,加入tag标签
为了更好的操作xml,可以在想要替换内容的部分加入标签tag="tag-name"。

以记事本的方式打开xml文件,查找节点,输入标签。
6.第六步,处理table数据列
table处理时,为了更好的找到数据列,所以给数据列加入tag="tr-content",结果如下图:

7.第七步,创建一般处理程序ExportFileHandler.ashx文件
准备一个扩展方法:
public static class Extensions
{
/// <summary>
/// 克隆一个节点
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public static XElement Clone(this XElement element)
{
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n =>
{
XElement e = n as XElement;
if (e != null)
{
return e.Clone();
}
return n;
}
),
(!element.IsEmpty && !element.Nodes().OfType<XText>().Any()) ? string.Empty : null
);
}
}View Code
具体执行代码:
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
context.Response.AddHeader("content-disposition", "attachment;filename=EmployeeReport.doc");
context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
context.Response.ContentType = "application/vnd.ms-word";
XDocument doc = XDocument.Load(context.Server.MapPath("~/Templete/测试.xml"));
//开始修改文档
XNamespace w = "http://schemas.microsoft.com/office/word/2003/wordml";
XNamespace wx = "http://schemas.microsoft.com/office/word/2003/auxHint";
var nodes = doc.Root.Element(w + "body").Descendants(w + "t");
FindAndReplaceNode(nodes, "name", "xxx的院子");
//填充表格
var table = doc.Root.Element(w + "body").Element(w + "tbl");//这是表格
var templateRow = doc.Root.Element(w + "body").Descendants(w + "tr").FirstOrDefault(x => x.Attribute("tag") != null && x.Attribute("tag").Value == "tr-content");
for (int i = 0; i < 10; i++)
{
var newRow = templateRow.Clone();
var datas = newRow.Descendants(w + "t");
FindAndReplaceNode(datas, "title", "标题");
FindAndReplaceNode(datas, "content", "这是一个测试");
FindAndReplaceNode(datas, "datetime", "2014-03-20");
table.Add(newRow);
}
templateRow.Remove();
StreamWriter sw = new StreamWriter(context.Response.OutputStream);
doc.Save(sw);
sw.Flush();
sw.Close();
context.Response.End();
}
private void FindAndReplaceNode(IEnumerable<XElement> elements, string tag, string value)
{
var found = elements.FirstOrDefault(n => n.Attribute("tag") != null && n.Attribute("tag").Value == tag);
if (found != null)
found.Value = value;
}View Code
8.第八步,运行程序,就可以得到一个你想要的word文档了
















