数据表到Excel电子表格

时间:2013-09-05 17:53:14

标签: vb.net sql-server-2008 tsql excel-interop

我正在尝试将数据表传递到我的子过程中。我收到错误,不确定为什么我收到错误。是否将我的列/行索引设置为0?

我的代码中的第67行是....

  

wBook.SaveAs(strFName)

enter image description here

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

1 个答案:

答案 0 :(得分:0)

好的,我发布后不久,我意识到我做了什么。 tdpInvoiceDate.Text包含对文件名不正确的字符。