最近在做一个根据模板导出excel的东西,思想是利用excel生的xml电子表格的xml,替换里面的内容,直接看代码吧
1 <?xml version="1.0"?>
2 <?mso-application prog>
2 <?mso-application prog>
.cs
1 XmlDocument xml = new XmlDocument();
2 xml.Load(Server.MapPath("~/Book1.xml"));
3 XmlNamespaceManager xnm = new XmlNamespaceManager(xml.NameTable);
4 //先为xml添加命名空间,否则selectNode无效
5 xnm.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
6 xnm.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
7 xnm.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
8 xnm.AddNamespace("html", "http://www.w3.org/TR/REC-html40");
9 //更改姓名,方法是为要输入的单元格命名,用xpath找到该单元格在xml的结点,并找到该结点的前一个结点即为所要找的结点,为它赋值
10 xml.SelectSingleNode("//ss:NamedCell[@ss:Name='姓名']", xnm).PreviousSibling.InnerText = this.TextBox1.Text;
11 //更改年龄
12 xml.SelectSingleNode("//ss:NamedCell[@ss:Name='年龄']", xnm).PreviousSibling.InnerText = this.TextBox2.Text;
13
14 //输出xml为xls
15 Response.Clear();
16 Response.ContentType = "application/x-excel";
17 Response.AppendHeader("Content-Disposition", "attachment; filename=test.xls");
18 Response.Write(xml.InnerXml);
19 Response.End();
2 xml.Load(Server.MapPath("~/Book1.xml"));
3 XmlNamespaceManager xnm = new XmlNamespaceManager(xml.NameTable);
4 //先为xml添加命名空间,否则selectNode无效
5 xnm.AddNamespace("o", "urn:schemas-microsoft-com:office:office");
6 xnm.AddNamespace("x", "urn:schemas-microsoft-com:office:excel");
7 xnm.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");
8 xnm.AddNamespace("html", "http://www.w3.org/TR/REC-html40");
9 //更改姓名,方法是为要输入的单元格命名,用xpath找到该单元格在xml的结点,并找到该结点的前一个结点即为所要找的结点,为它赋值
10 xml.SelectSingleNode("//ss:NamedCell[@ss:Name='姓名']", xnm).PreviousSibling.InnerText = this.TextBox1.Text;
11 //更改年龄
12 xml.SelectSingleNode("//ss:NamedCell[@ss:Name='年龄']", xnm).PreviousSibling.InnerText = this.TextBox2.Text;
13
14 //输出xml为xls
15 Response.Clear();
16 Response.ContentType = "application/x-excel";
17 Response.AppendHeader("Content-Disposition", "attachment; filename=test.xls");
18 Response.Write(xml.InnerXml);
19 Response.End();
其实最后还是xml的,不过改了扩展名为xls