Public Sub ExportXLsD()
Dim Mytable As New DataTable
'Mytable = CType(datagrid.DataSource, DataTable)
If Mytable Is Nothing Then
MessageBox.Show("没有记录不能导出数据", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Sub
End If
Mytable.Columns.Add("c1")
Mytable.Columns.Add("c2")
Mytable.Columns.Add("c3")
Mytable.Rows.Add("a1", "a2", "a3")
Mytable.Rows.Add("a4", "a5", "a6")
If Mytable.Rows.Count > 0 Then
Dim MyFileName As String
Dim FileName As String = ""
With SaveFileDialog1
.AddExtension = True '如果用户忘记添加扩展名,将自动加上
.DefaultExt = "xls" '默认扩展名
.Filter = "Excel文件(*.xls)|*.xls"
.Title = "文件保存到"
If .ShowDialog = DialogResult.OK Then
FileName = .FileName
End If
End With
MyFileName = Microsoft.VisualBasic.Right(FileName, 4)
If MyFileName = "" Then
Exit Sub
End If
If MyFileName = ".xls" Or MyFileName = ".XLS" Then
Dim FS As FileStream = New FileStream(FileName, FileMode.Create)
Dim sw As StreamWriter = New StreamWriter(FS, System.Text.Encoding.Default)
'sw.WriteLine(vbTab & FileName & vbTab & Date.Now)
Dim i, j As Integer
Dim str As String = ""
For i = 0 To Mytable.Columns.Count - 1
str = Mytable.Columns(i).Caption
sw.Write(str & vbTab)
Next
sw.Write(vbCrLf)
For j = 0 To Mytable.Rows.Count - 1
For i = 0 To Mytable.Columns.Count - 1
Dim strRow As String
strRow = IIf(Mytable.Rows(j).Item(i) Is DBNull.Value, "", Mytable.Rows(j).Item(i))
sw.Write(strRow & vbTab)
Next
sw.Write(vbLf)
Next
sw.Close()
FS.Close()
MessageBox.Show("数据导出成功!", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Exit Sub
End If
Else
MessageBox.Show("没有记录不能导出数据", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub