在CSDN 討論中發現一個不錯的匯出excel方式,原處
底下為我整理過,並測寫的結果:
底下為程式碼:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim tba As New DataTable
tba.Columns.Add("t1", GetType(System.String))
tba.Columns.Add("t2", GetType(System.String))
Dim row As DataRow
row = tba.NewRow
row("t1") = "自己輸入值"
row("t2") = "自己輸入值"
tba.Rows.Add(row)
DGridView1.DataSource = tba
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call DataToExcel(DGridView1)
End Sub
Public Sub DataToExcel(ByVal m_DataView As DataGridView)
Dim kk As New SaveFileDialog()
kk.Title = "儲存EXECL文件"
kk.Filter = "EXECL文件(*.xls) |*.xls |所有文件(*.*) |*.*"
kk.FilterIndex = 1
If kk.ShowDialog() = DialogResult.OK Then
Dim FileName As String = kk.FileName ' + ".xls"
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.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.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(vbLf) > 0 Then
rowstr = rowstr.Replace(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
End Class
沒有留言:
張貼留言