xslt+xml生成Excel

  做了个Excel的导出,Excel的表头和表尾有些麻烦,就想着用xslt模板来做。期间碰到了一些问题。

  如果只是根据xslt转换xml的话,下面的代码就可以实现:

  
 1 ''' <summary>
 2     ''' Xml2Excel
 3     ''' </summary>
 4     ''' <param name="xsltName">模板文件</param>
 5     ''' <param name="xmlName">xml文件</param>
 6     ''' <param name="xlsName">excel文件</param>
 7     Sub Xml2Excel(xsltName As String, xmlName As String, xlsName As String)
 8         Dim xmlDoc As Xml.XmlDocument = New Xml.XmlDocument()
 9         Dim proc As XslCompiledTransform = New XslCompiledTransform()
10         Dim writer As XmlTextWriter = New XmlTextWriter(xlsName, System.Text.Encoding.Unicode)
11 
12         xmlDoc.Load(xmlName)
13         proc.Load(xsltName)
14         writer.WriteProcessingInstruction("xml", "version='1.0'")
15 
16         proc.Transform(xmlDoc, Nothing, writer)
17 
18         writer.Close()
19 
20     End Sub
xml2Excel

  打开这个导出后的文件发现,其实这个还是xml,只是以excel的方式呈现。所以还需要将xml转换成excel

  
 1 Imports OIE = Microsoft.Office.Interop.Excel
 2 
 3     ''' <summary>
 4     ''' 把xml转存为excel
 5     ''' </summary>
 6     ''' <param name="tempExcelFileName"></param>
 7     ''' <param name="excleFileName"></param>
 8     Private Sub ConvertToExcel(tempExcelFileName As String, excleFileName As String)
 9 
10         Dim missing As Object = Reflection.Missing.Value
11         Dim excel As OIE.ApplicationClass
12         Dim workbook As OIE._Workbook
13         excel = New OIE.ApplicationClass()
14         Try
15 
16             'workbook=excel.Workbooks.Open(tempExcelFileName,0,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing);
17             workbook = excel.Workbooks.OpenXML(tempExcelFileName, 1, 1) '/New Object[]{1,New Object[]{"A"}}
18 
19             workbook.SaveAs(excleFileName,
20                             OIE.XlFileFormat.xlWorkbookNormal,'Excel的格式
21                             missing,
22                             missing,
23                             False,
24                             False,
25                             OIE.XlSaveAsAccessMode.xlNoChange,
26                             False,
27                             missing,
28                             missing,
29                             missing,
30                             missing)
31 
32             IO.File.Delete(tempExcelFileName)
33 
34         Catch ex As Exception
35             Throw ex
36         Finally
37             excel.Quit()
38             excel = Nothing
39         End Try
40     End Sub
ConvertToExcel

  需要注意的是SaveAs中的参数fileFormat(保存的文件格式),保存的excel版本要和本机上的版本一直,不然会有HRESULT:0x800A03EC异常。

  将Excel另存为xml文件,可以快速生成一个xslt文件,然后根据xslt格式修改此模板文件。注意将表格中的ss:ExpandedColumnCount 属性去掉。此属性表示表格的可扩展行数,不然转换后的文件可能无法打开。

  

  此链接关于Excel的一些属性描述挺清楚: http://zhangzhongjie.iteye.com/blog/1779891


  

posted @ 2018-03-13 10:44  Xiaoooo  阅读(858)  评论(0编辑  收藏  举报