.Net中生成Excel文件一般需要導入COM控件,本文介紹利用Office 2003 Schemas創建Excel文件的實踐。
微軟發布了Office 2003 Schemas,小雞射手采用XSLT方法試驗了通過Office 2003 Schemas創建Excel文件的方法。轉換文件Transform.xsl定義如下:
<?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/"> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <Worksheet ss:Name="myPage"> <Table> <xsl:for-each select="catalog/cd"> <Row> <Cell><Data ss:Type="String"><xsl:value-of select="@title"/></Data></Cell> <Cell><Data ss:Type="String"><xsl:value-of select="@description"/></Data></Cell> </Row> </xsl:for-each> </Table> </Worksheet> </Workbook> </xsl:template></xsl:stylesheet>
主要試驗代碼如下:
DataSet ds = new DataSet(); DataTable table = new DataTable("TestDataTable"); table.Columns.Add("title", typeof(string)); table.Columns.Add("description", typeof(string)); table.Rows.Add(new object[]{"blog", "I love it!"}); table.Rows.Add(new object[]{"csdn", "China's msdn"}); ds.Tables.Add(table);
XmlDocument doc = new XmlDocument(); doc.LoadXml(ds.GetXml()); XPathNavigator nav = doc.DocumentElement.CreateNavigator();
XmlTextWriter writer = new XmlTextWriter("output.xls", null); writer.WriteProcessingInstruction("xml", "version=\"1.0\""); XslTransform transform = new XslTransform(); transform.Load("Transform.xsl"); transform.Transform(nav, null,writer,null); writer.Close();
這只是最簡單的試驗,通過Schema可以完成幾乎任何Excel/Word等的功能;學習中.....,嘻嘻!最后說一句,該方法無需安裝Office 2003。
|