将Dataset导出到Excel
代码如下:
先得引用Excel组件。
其中,mydata是我的Dataset信息。对信息进行逐行填充,最后输出。
Try
Dim selEmployeeContract As String = "Select * from * "
Dim dsEmployeeContract As DataSet = New DataSet
dsEmployeeContract = mydata
If dsEmployeeContract Is Nothing Then
MsgBox("没有数据,无法导出!", MsgBoxStyle.OkOnly)
Exit Sub
Else
Dim xlsapp As New Excel.Application
xlsapp.Workbooks.Add()
xlsapp.Visible = True
xlsapp.Selection.Merge()
Dim i As Int16
For i = 1 To dsEmployeeContract.Tables(0).Columns.Count
xlsapp.Cells(1, i) = dsEmployeeContract.Tables(0).Columns(i - 1).ColumnName
Next
Dim rowindex As Integer = 2
Dim colindex As Integer
Dim col As DataColumn
Dim row As DataRow
Dim nxh As Integer = 1
For Each row In dsEmployeeContract.Tables(0).Rows
colindex = 1
For Each col In dsEmployeeContract.Tables(0).Columns
If colindex = 1 Then
xlsapp.Cells(rowindex, colindex) = RTrim(Convert.ToString(row(col.ColumnName)))
Else
xlsapp.Cells(rowindex, colindex) = RTrim(Convert.ToString(row(col.ColumnName)))
End If
colindex += 1
Next
rowindex += 1
nxh += 1
Next
xlsapp.Range(xlsapp.Cells(2, 1), xlsapp.Cells(dsEmployeeContract.Tables(0).Rows.Count + 2, dsEmployeeContract.Tables(0).Columns.Count)).Font.Size = 9
xlsapp.Range(xlsapp.Cells(2, 6), xlsapp.Cells(dsEmployeeContract.Tables(0).Rows.Count + 2, 4)).NumberFormat = "yyyy-MM-dd"
xlsapp.Range(xlsapp.Cells(2, 7), xlsapp.Cells(dsEmployeeContract.Tables(0).Rows.Count + 2, 5)).NumberFormat = "yyyy-MM-dd"
xlsapp.Columns.AutoFit()
End If
Catch ex As Exception
MsgBox(ex.ToString(), MsgBoxStyle.Critical)
End Try