在.NET環境下將報表數據導出Excel和Word

發表于:2008-04-23來源:作者:點擊數: 標簽:ExcelNETWordnet環境
在 VB 6 開發 環境下,本人使用EXCEL作過報表,在.NET環境下開發,本人使用水晶報表。但VB.NET同樣可以將報表導出到EXCEL和WORD進行輸出,制作出專業水平的報表。 具體操作如下:(注:首先需添加引用,選擇COM,選擇Microsoft Word 10.0 Object Library和Mic
 在VB6開發環境下,本人使用EXCEL作過報表,在.NET環境下開發,本人使用水晶報表。但VB.NET同樣可以將報表導出到EXCEL和WORD進行輸出,制作出專業水平的報表。

  具體操作如下:(注:首先需添加引用,選擇COM,選擇Microsoft Word 10.0 Object Library和Microsoft Excel 10.0 Object Library組件)

  1.先創建一個DataTable,作為數據來源,也可以另將其它的數據源。

  Private Function CreaTable() As DataTable
  Dim dt As New DataTable()
  dt.Columns.Add("列1", GetType(String))
  dt.Columns.Add("列2", GetType(Integer))
  dt.Columns.Add("列3", GetType(String))
  dt.Columns.Add("列4", GetType(String))
  Dim row, row1 As DataRow
  row = dt.NewRow()
  row!列1 = "行1"
  row!列2 = 1
  row!列3 = "d"
  row!列4 = "a"
  dt.Rows.Add(row)
  row1 = dt.NewRow()
  row1!列1 = "行2"
  row1!列2 = 12
  row1!列3 = "b"
  row1!列4 = "c"
  dt.Rows.Add(row1)
  Return dt
  End Function

  2.將表中的內容導出到Excel

  Dim xlApp As New Excel.Application()
  Dim xlBook As Excel.Workbook
  Dim xlSheet As Excel.Worksheet
  Dim rowIndex, colIndex As Integer
  rowIndex = 1
  colIndex = 0
  xlBook = xlApp.Workbooks().Add
  xlSheet = xlBook.Worksheets("sheet1")
  Dim Table As New DataTable()
  Table = CreaTable()
  '將所得到的表的列名,賦值給單元格
  Dim Col As DataColumn
  Dim Row As DataRow
  For Each Col In Table.Columns
  colIndex = colIndex + 1
  xlApp.Cells(1, colIndex) = Col.ColumnName
  Next
  '得到的表所有行,賦值給單元格
  For Each Row In Table.Rows
  rowIndex = rowIndex + 1
  colIndex = 0
  For Each Col In Table.Columns
  colIndex = colIndex + 1
  xlApp.Cells(rowIndex, colIndex) = Row(Col.ColumnName)
  Next
  Next
  With xlSheet
  .Range(.Cells(1, 1), .Cells(1, colIndex)).Font.Name = "黑體"
  '設標題為黑體字
  .Range(.Cells(1, 1), .Cells(1, colIndex)).Font.Bold = True
  '標題字體加粗
  .Range(.Cells(1, 1), .Cells(rowIndex, colIndex)).Borders.LineStyle = 1
  '設表格邊框樣式
  End With
  With xlSheet.PageSetup
  .LeftHeader = "" & Chr(10) & "&""楷體_GB2312,常規""&10公司名稱:" ' & Gsmc
  .CenterHeader = "&""楷體_GB2312,常規""公司人員情況表&""宋體,常規""" & Chr(10) & "&""楷體_GB2312,常規""&10日 期:"
  .RightHeader = "" & Chr(10) & "&""楷體_GB2312,常規""&10單位:"
  .LeftFooter = "&""楷體_GB2312,常規""&10制表人:"
  .CenterFooter = "&""楷體_GB2312,常規""&10制表日期:"
  .RightFooter = "&""楷體_GB2312,常規""&10第&P頁 共&N頁"
  End With
  xlApp.Visible = True

  

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97