简体   繁体   中英

Data Table to Excel spreadsheet

I'm trying to pass a data table into my sub procedure. I am getting an error and am unsure why I am getting the error. Is it something with my column/row indexes being set to 0?

Line 67 in my code is....

wBook.SaveAs(strFName)

在此处输入图片说明

Private Sub DataTableToExcel(ByVal dtTemp As DataTable)
        Try
            Dim _excel As New Microsoft.Office.Interop.Excel.Application
            Dim wBook As Microsoft.Office.Interop.Excel.Workbook
            Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

            wBook = _excel.Workbooks.Add()
            wSheet = wBook.ActiveSheet()

            Dim dt As System.Data.DataTable = dtTemp
            Dim dc As System.Data.DataColumn
            Dim dr As System.Data.DataRow
            Dim cIndex As Integer = 0
            Dim rIndex As Integer = 0

            For Each dc In dt.Columns
                cIndex = cIndex + 1
                _excel.Cells(1, cIndex) = dc.ColumnName
            Next

            For Each dr In dt.Rows
                rIndex = rIndex + 1
                cIndex = 0
                For Each dc In dt.Columns
                    cIndex = cIndex + 1
                    _excel.Cells(rIndex + 1, cIndex) = dr(dc.ColumnName)
                Next
            Next

            wSheet.Columns.AutoFit()
            Dim strFName As String = "H:\RawDataReport\" & txtGPSystemNum.Text & dtpInvoiceDate.Text & _
                                        ".xlsx"
            If System.IO.File.Exists(strFName) Then
                System.IO.File.Delete(strFName)
            End If

            wBook.SaveAs(strFName)
            wBook.Close()
            _excel.Quit()

        Catch ex As Exception
            MessageBox.Show(ex.ToString())
        End Try
    End Sub

Ok, shortly after I posted this I realized what I did. tdpInvoiceDate.Text contained characters that weren't correct for a filename.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM