生成Excel工作表崩溃

时间:2019-06-12 16:04:57

标签: sql excel vb.net

我有一个查询数据库并构造excel文件的函数。但是,当我没有完成数据导入时单击进入Excel时,我遇到了崩溃。除了点击之外,一切都完美无缺。

System.Runtime.InteropServices.COMException:'HRESULT异常:0x800AC472'

任何帮助将不胜感激

Private Sub cmdExcel_Click(sender As Object, e As EventArgs) Handles Excel.Click

        Dim appXL As Excel.Application
        Dim wbXl As Excel.Workbook
        Dim shXL As Excel.Worksheet
        Dim raXL As Excel.Range

        appXL = CreateObject("Excel.Application")
        appXL.Visible = True

        wbXl = appXL.Workbooks.Add
        shXL = wbXl.ActiveSheet


        shXL.Cells(1, 1).Value = "Statement_No"
        shXL.Cells(1, 2).Value = "Statement_Date"
        shXL.Cells(1, 3).Value = "Invoice_No"




        sConnectionString = _conn

        Dim conn As New SqlConnection(sConnectionString)

        Dim dr As SqlDataReader

        sSQL = "select Statement_No, Statement_Date, Invoice_No, Invoice_Date 
                FROM dbo.Vw_Summary_Invoice('num1',NULL, '" & dateStart.Value.ToString("yyyyMMdd") & "','" & dateEnd.Value.ToString("yyyyMMdd") & " 23:59:59',0,0) As TInv


        Dim cmd As New SqlCommand(sSQL, conn)


        conn.Open()

        dr = cmd.ExecuteReader()
        Dim j = 2

        Do While dr.Read()

            With shXL

                For i As Integer = 0 To dr.FieldCount - 1

                    Select Case dr.GetName(i).ToString()

                        Case "Statement_Date"
                            If dr.Item(i).ToString.Length > 0 Then
                                .Cells(j, i + 1).Value = Convert.ToDateTime(dr.Item(i)).ToString("yyyy-MM-dd")
                            End If

                        Case "Invoice_Date"
                            If dr.Item(i).ToString.Length > 0 Then
                                .Cells(j, i + 1).Value = Convert.ToDateTime(dr.Item(i)).ToString("yyyy-MM-dd")
                            End If

                        Case Else

                            .Cells(j, i + 1).Value = dr.Item(i)
                    End Select
                Next

                j = j + 1

            End With




        Loop

        dr.Close()
        conn.Close()


        raXL = shXL.Range("A1", "AD" & j)


        raXL.EntireColumn.AutoFit()

        appXL.Visible = True
        appXL.UserControl = True


        raXL = Nothing
        shXL = Nothing
        wbXl = Nothing

        appXL = Nothing

        MsgBox("process Over.")

        Dispose()

    End Sub

0 个答案:

没有答案