Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
Dim sPath As String = String.Empty
Dim dlgSave As New SaveFileDialog()
Dim dt As New DataTable
dlgSave.DefaultExt = "xls"
dlgSave.Filter = "Microsoft Excel|*.xls"
dlgSave.InitialDirectory = Application.StartupPath
If dlgSave.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
xlApp = New Microsoft.Office.Interop.Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
For k As Integer = 1 To DataGridView1.Columns.Count
xlWorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
Next
Me.ProgressBar1.Visible = True
Me.Label14.Visible = True
Me.ProgressBar1.Minimum = 0
Me.ProgressBar1.Maximum = DataGridView1.Rows.Count
UpdatePBar()
Next
If Me.ProgressBar1.Maximum > Me.ProgressBar1.Value + 1 Then
Me.ProgressBar1.Value = Me.ProgressBar1.Value + 1
End If
Next
xlWorkSheet.Columns.AutoFit()
Dim sFileName As String = Replace(dlgSave.FileName, ".xlsx", "xlx")
If System.IO.File.Exists(sFileName) Then
System.IO.File.Delete(sFileName)
End If
xlWorkSheet.SaveAs(sFileName)
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
dt = Nothing
Me.ProgressBar1.Value = 0
Me.ProgressBar1.Visible = False
Me.Label14.Visible = False
MsgBox("ไฟล์ของคุณสมบูรณ์แล้ว", MsgBoxStyle.Information, "Transport Cost system")
Catch ex As Exception
MsgBox(ErrorToString)
End Try
End If
Tag : .NET, Ms SQL Server 2008, VB.NET, VS 2010 (.NET 4.x), Windows