Dim myexcel As New Excel.Application
Dim mybook As New Excel.Workbook
Dim mysheet As New Excel.Worksheet
Set mybook = myexcel.Workbooks.Add '添加一个新的BOOK
Set mysheet = mybook.Worksheets.Add '添加一个新的SHEET
myexcel.visible=true
Private Sub DataToExcel(ByVal Dtg As DataGrid)
'--com+ 添加 Excel9.0LB的引用
Try
Dim dt As DataTable
dt = Dtg.DataSource()
Dim i, j As Integer
Dim myexcel As New Excel.Application
Dim mybook As Excel.Workbook
Dim mysheet As Excel.Worksheet
mybook = myexcel.Workbooks.Add '添加一个新的BOOK
mysheet = mybook.Worksheets("sheet1") '添加一个新的SHEET
mysheet.Range("a1", Chr(Asc("a") + dt.Columns.Count()) + "1").Merge()
mysheet.Cells(1, 1) = "合并报表项目"
For j = 1 To dt.Columns.Count()
mysheet.Cells(2, j) = dt.Columns(j - 1).Caption()
Next
For i = dt.Rows.Count() + 2 To 3 Step -1
For j = 1 To dt.Columns.Count()
If dt.Rows(i - 3)(j - 1).ToString() = "" Then
' Me.RichTextBox1.AppendText("this is null")
Else
' Me.RichTextBox1.AppendText(dt.Rows(i - 3)(j - 1).ToString())
mysheet.Cells(i, j) = dt.Rows(i - 3)(j - 1).ToString()
End If
Next j
' Me.RichTextBox1.AppendText("i=" + i.ToString() + " posnum=" + dt.Rows(0)(2).ToString() + " ")
Next i
'myexcel.Visible = True
'保存文件
mybook.SaveAs("..\ceshiExport") '保存文件
mybook.Close()
myexcel.Quit()
Catch ex As Exception
MsgBox(ex.StackTrace())
MsgBox(ex.ToString())
End Try
End Sub