飞狐.net

人的每一步行动,都在书写自己的历史
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

由DataView导出Excel的类

Posted on 2006-12-15 22:40  飞狐时代  阅读(691)  评论(0)    收藏  举报
 在项目中经常用来与Excel来处理报表的功能,比如从界面上读出数据库的数据,然后导出到Excel。以下就是导出Excel的类。注:添加Excel的引用,名称为Microsoft Excel 11.0 Object Library,然后引入Excel的命名空间。代码如下:
Imports System
Imports System.Data
Imports System.IO
Imports Excel
Imports System.Diagnostics
Imports System.Data.SqlClient

Public Class ExportToExcel
    
Public Sub DataViewtToExcel(ByVal dv As DataView, ByVal fileName As String)
        
Dim xlApp As New Excel.Application
        
Dim xlBook As Excel.Workbook
        
Dim xlSheet As Excel.Worksheet
        
Dim xbookname As String = ""
        
Dim rowIndex, colIndex As Integer
        
Dim myTable As System.Data.DataTable
     
            rowIndex 
= 1
            colIndex 
= 0

        xbookname 
= fileName
        
If File.Exists(xbookname) Then
            xlBook 
= xlApp.Workbooks.Add(xbookname)
        
Else
            xlBook 
= xlApp.Workbooks.Add()
            
'xlBook.SaveAs(xBookname)
        End If

        xlSheet 
= xlBook.Worksheets("sheet1")
        
'获取筛选后的结果,以作为输出源。

        myTable 
= dv.Table
        
'将所得到的表的列名,赋值给单元格
        Dim Col As DataColumn
        
Dim Row As DataRow
        
For Each Col In myTable.Columns
            colIndex 
= colIndex + 1
            xlApp.Cells(
1, colIndex) = Col.ColumnName
        
Next

        
'得到的表所有行,赋值给单元格
        For Each Row In myTable.Rows
            rowIndex 
= rowIndex + 1
            colIndex 
= 0
            
For Each Col In myTable.Columns
                colIndex 
= colIndex + 1
                xlApp.Cells(rowIndex, colIndex) 
= Row(Col.ColumnName)
            
Next
        
Next

        
With xlSheet
            
'设标题为宋体字
            .Range(.Cells(11), .Cells(1, colIndex)).Font.Name = "宋体"
            
'标题字体加粗
            .Range(.Cells(11), .Cells(1, colIndex)).Font.Bold = True
            
'设表格边框样式
            .Range(.Cells(11), .Cells(rowIndex, colIndex)).Borders.LineStyle = 1
            
'设表格字体
            .Range(.Cells(21), .Cells(rowIndex, colIndex)).Font.Name = "宋体"
            .Range(.Cells(
21), .Cells(rowIndex, colIndex)).Font.Size = 11
            .Range(.Cells(
21), .Cells(rowIndex, colIndex)).Font.Bold = False
        
End With

        
'xlapp.Visible = True
        xlBook.Saved = True
        xlApp.UserControl 
= False
        xlBook.SaveAs(xbookname)
        
'xlapp.ActiveWorkbook.SaveCopyAs(xBookname)
        xlApp.Quit()
        KillProcess(
"EXCEL")

    
End Sub


    
Public Sub KillProcess(ByVal processName As String)
            
For Each thisproc As Process In Process.GetProcessesByName(processName)
                
If thisproc.CloseMainWindow = False Then
                    thisproc.Kill()
                
End If
            
Next
    
End Sub


End Class

飞狐.net·书写程序员的历史·创建于2006年12月
Copyright 2005 Silver fox© 飞狐.net All Rights Reserved.