将查询结果写入xls文件时缺少最后一行

时间:2011-07-22 15:46:45

标签: asp.net vb.net for-loop streamwriter

我有一个例程,用于获取查询结果并将它们写入xls文件。问题是我只获取列标题和3行数据中的2行。如果没有将最后一行数据写入文件,我做错了什么?

谢谢!

   Public Sub DsiplayQueryandConvertoXls(ByVal ReprtID As Integer, ByVal pgid As Integer, ByVal GroupName As String, ByVal outputPath As String)
            Dim i As Integer
            Dim strLine As String, filePath, fileName, fileExcel, link
            Dim objFileStream As FileStream
            Dim objStreamWriter As StreamWriter
            'Dim nRandom As Random = New Random(DateTime.Now.Millisecond)
            Dim fs As Object, myFile As Object
            Dim cnn As SqlConnection = New SqlConnection("Data Source=db;Initial Catalog=productionservicereminder;User Id=user;Password=pass;")

            'Create a file name.
            If ReprtID = 1 Then
                fileExcel = GroupName & "ExtWarrantyReport.xls"
            End If

            'Set a virtual folder to save the file.
            'Make sure that you change the application name to match your folder.
            If ReprtID = 1 Then
                filePath = outputPath
            End If

            fileName = filePath & fileExcel

            'Use FileStream to create the .xls file.
            objFileStream = New FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)
            objStreamWriter = New StreamWriter(objFileStream)

            'Use a DataReader to connect to the Pubs database.
            cnn.Open()
            Dim sql3 As String = "select * from table"
            Dim cmd As SqlCommand = New SqlCommand(sql3, cnn)
            Dim drr As SqlDataReader
            cmd.Parameters.Add(New SqlParameter("@pgid", pgid))
            drr = cmd.ExecuteReader()
            drr.Read()
            'Enumerate the field names and records that are used to build the file.
            For i = 0 To drr.FieldCount - 1
                strLine = strLine & drr.GetName(i).ToString & Chr(9)
            Next

            'Write the field name information to file.
            objStreamWriter.WriteLine(strLine)

            'Reinitialize the string for data.
            strLine = ""

            'Enumerate the database that is used to populate the file.
            While drr.Read()
                For i = 0 To drr.FieldCount - 1
                    strLine = strLine & drr.GetValue(i) & Chr(9)
                Next
                objStreamWriter.WriteLine(strLine)
                strLine = ""
            End While

 'Clean up.
        drr.Close()
        cnn.Close()
        objStreamWriter.Close()
        objFileStream.Close()
End Sub

2 个答案:

答案 0 :(得分:0)

您需要确保在打开的任何流上调用CloseFlush也很有用。

编辑:

查看Using声明 - 确保您的IDisposable获得Disposed

Using file =  File.OpenWrite("myfile.txt")

   file.WriteLine("Hello World!")

End Using

答案 1 :(得分:0)

处理并关闭流,以便写入最后一个缓冲区