简体   繁体   English

如何导出到.csv文件

[英]How to export to a .csv file

I have a basic VB.net program that runs a query against a database to extract customer information to send coupons. 我有一个基本的VB.net程序,该程序对数据库运行查询以提取客户信息以发送优惠券。 What I'd like to do, is when I push a command button to return the results and create a .csv file on the computer that runs the program... Right now, I have a program that runs the query, and dumps the results to report viewer, however I cannot export to .csv, and there are too many records to show on the report viewer... 我想做的是,当我按下命令按钮以返回结果并在运行该程序的计算机上创建一个.csv文件时...现在,我有一个程序运行查询并转储结果返回到报表查看器,但是我无法导出到.csv,并且报表查看器上显示的记录太多...

Here is my code so far... I assume I need to build the layout in XML form? 到目前为止,这是我的代码...我假设我需要以XML格式构建布局?

    Dim str As New StringBuilder

            For Each dr As DataRow In Me.DataDeliveryServiceDataSet.Invoice_Tb

                For Each field As Object In dr.ItemArray

                    str.Append(field.ToString & ",")

                Next

                str.Replace(",", vbNewLine, str.Length - 1, 1)

            Next



            Try

                My.Computer.FileSystem.WriteAllText("C:\temp\testcsv.csv", str.ToString, False)

            Catch ex As Exception

                MessageBox.Show("Write Error")
End Try
End Sub

You could replace the inner loop with this short version using LinQ 您可以使用LinQ用此简短版本替换内部循环

Dim str As New StringBuilder 
For Each dr As DataRow In Me.DataDeliveryServiceDataSet.Invoice_Tb 
    str.AppendLine(string.Join(",", _ 
             dr.ItemArray.Select(Function(o) if(o = DBNull.Value,"",o.ToString()))))
Next 

of course, if you need to export in XML format is enough to use the WriteXml method of the datatable 当然,如果您需要导出为XML格式就足以使用数据表的WriteXml方法

Me.DataDeliveryServiceDataSet.Invoice_Tb.WriteXml("C:\temp\testcsv.csv")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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