网上找了很久一般都是C#版本的DataGridView 导出到excel,vb.net版本的非常 少,这次我整理了一下,可实现不需要excel控件就能导出到excel csv或xls,以下是具体代码
ASP/Visual Basic Code复制内容到剪贴板
- Public Sub DataToExcel(m_DataView As DataGridView)
- Dim kk As New SaveFileDialog()
- kk.Title = "保存EXECL文件"
- kk.Filter = "EXECL文件(*.csv) |*.csv |EXECL文件(*.xls) |*.xls |所有文件(*.*) |*.*"
- kk.FilterIndex = 1
- kk.FileName = "name_" & TextBox1.Text
- If kk.ShowDialog() = DialogResult.OK Then
- Dim FileName As String = kk.FileName '+ ".csv"
- If File.Exists(FileName) Then
- File.Delete(FileName)
- End If
- Dim objFileStream As FileStream
- Dim objStreamWriter As StreamWriter
- Dim strLine As String = ""
- objFileStream = New FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write)
- objStreamWriter = New StreamWriter(objFileStream, System.Text.Encoding.Unicode)
- For i As Integer = 0 To m_DataView.Columns.Count - 1
- If m_DataView.Columns(i).Visible = True Then
- strLine = (strLine & m_DataView.Columns(i).HeaderText.ToString()) + Convert.ToChar(9)
- End If
- Next
- objStreamWriter.WriteLine(strLine)
- strLine = ""
- For i As Integer = 0 To m_DataView.Rows.Count - 1
- If m_DataView.Columns(0).Visible = True Then
- If m_DataView.Rows(i).Cells(0).Value Is Nothing Then
- strLine = (strLine & Convert.ToString(" ")) + Convert.ToChar(9)
- Else
- strLine = (strLine & m_DataView.Rows(i).Cells(0).Value.ToString()) + Convert.ToChar(9)
- End If
- End If
- For j As Integer = 1 To m_DataView.Columns.Count - 1
- If m_DataView.Columns(j).Visible = True Then
- If m_DataView.Rows(i).Cells(j).Value Is Nothing Then
- strLine = (strLine & Convert.ToString(" ")) + Convert.ToChar(9)
- Else
- Dim rowstr As String = ""
- rowstr = m_DataView.Rows(i).Cells(j).Value.ToString()
- If rowstr.IndexOf(vbCr & vbLf) > 0 Then
- rowstr = rowstr.Replace(vbCr & vbLf, " ")
- End If
- If rowstr.IndexOf(vbTab) > 0 Then
- rowstr = rowstr.Replace(vbTab, " ")
- End If
- strLine = (strLine & rowstr) + Convert.ToChar(9)
- End If
- End If
- Next
- objStreamWriter.WriteLine(strLine)
- strLine = ""
- Next
- objStreamWriter.Close()
- objFileStream.Close()
- MessageBox.Show(Me, "保存EXCEL成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information)
- End If
- End Sub
最后去调用即可: DataToExcel(DataGridView1) '导出到excel
需要引用的是:Imports System.IO