none
請問Datagridview轉excel後不輸出直接存檔該如何改下列程式呢? RRS feed

  • 問題

  • 親愛的大大:

          以下的程式是可以直接輸出Excel 但我想直接輸出成檔案並直接給他檔名不須再儲存請問我該如何改呢?

    Public Sub ExportDataGridViewToExcel(ByVal DataGridView1 As DataGridView)
            Dim MyExcel As New Microsoft.Office.Interop.Excel.Application()
            MyExcel.Application.Workbooks.Add()
            MyExcel.Visible = True
            '獲取標題
            Dim Cols As Integer
            For Cols = 1 To DataGridView1.Columns.Count
                MyExcel.Cells(1, Cols) = DataGridView1.Columns(Cols - 1).HeaderText
            Next
            '往excel表裡添加資料()
            Dim i As Integer
            For i = 0 To DataGridView1.RowCount - 1
                Dim j As Integer
                For j = 0 To DataGridView1.ColumnCount - 1
                    If Me.DataGridView1(j, i).Value Is System.DBNull.Value Or DataGridView1(j, i).Value Is Nothing Then

                        MyExcel.Cells(i + 2, j + 1) = ""
                    Else
                        MyExcel.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString
                    End If
                Next j
            Next i

        End Sub

    謝謝各位大大

    2015年1月29日 上午 06:52

解答

  •         xlWorkBook = MyExcel.Application.Workbooks.Add()
    MyExcel.DisplayAlerts = False
            MyExcel.Visible = False
            '獲取標題
            Dim Cols As Integer
            For Cols = 1 To DataGridView1.Columns.Count
                MyExcel.Cells(1, Cols) = DataGridView1.Columns(Cols - 1).HeaderText
            Next
            '往excel表裡添加資料()
            Dim i As Integer
            For i = 0 To DataGridView1.RowCount - 1
                Dim j As Integer
                For j = 0 To DataGridView1.ColumnCount - 1
                    If Me.DataGridView1(j, i).Value Is System.DBNull.Value Or DataGridView1(j, i).Value Is Nothing Then
                        MyExcel.Cells(i + 2, j + 1) = ""
                    Else
                        MyExcel.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString
                    End If
                Next j
            Next i
    
    xlWorkBook.SaveAs("d:\test1.xls")
    xlWorkBook.Close()

    VB.NET 簡單的 Excel 檔讀寫

    http://iammic.pixnet.net/blog/post/31168790-vb.net-%E7%B0%A1%E5%96%AE%E7%9A%84-excel-%E6%AA%94%E8%AE%80%E5%AF%AB

    2015年1月29日 上午 07:16

所有回覆