如何使用VB设计CSV文件?

时间:2012-04-18 04:55:13

标签: asp.net vb.net

在我的项目中,我正在创建一个CSV文件,但我想改变它的设计。请帮帮我:

 Private Sub ExportDataToCSV()
    Dim fileName As String = "CheckRegistrationStatus_" & Format(Now, "yyyyMMddhhmms") & ".csv"
    HttpContext.Current.Response.Clear()
    ' Set the response headers to fit our CSV file 
    HttpContext.Current.Response.ContentType = "text/plain"
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" & fileName)
    Using writer As New System.IO.StreamWriter(HttpContext.Current.Response.OutputStream)
        Dim columnHeader As String = String.Empty
        For i As Integer = 0 To grd1.Columns.Count - 1
            columnHeader += grd1.Columns(i).HeaderText & IIf(i < grd1.Columns.Count - 1, ",", "").ToString()
        Next
        writer.WriteLine(columnHeader)
        'writer.WriteLine(AddCSVHeaderRow()) ' Only if you need custom headers to be added
        ' Add all the data rows 
        For Each row As GridViewRow In grd1.Rows
            writer.WriteLine(GetCSVLine(row.Cells))
        Next
    End Using
    ' End the current response. Otherwise, excel will open with the whole page inside.
    HttpContext.Current.Response.End()
End Sub
Private Shared Function GetCSVLine(ByVal cellsToAdd As TableCellCollection) As String
    Dim line As String = String.Empty
    Dim isFirst As Boolean = True
    For Each cell As TableCell In cellsToAdd
        If Not isFirst Then
            line += ","
        End If
        isFirst = False
        line += """" & Replace(cell.Text, "&nbsp;", "") & """"
    Next
    Return line
End Function

正在显示输出,如下图所示。但我想使标题加粗并扩展列宽。请帮帮我。

enter image description here

2 个答案:

答案 0 :(得分:2)

你做不到。 CSV文件格式是纯数据格式。它无法设置字体,列宽或与样式相关的任何其他内容。

此外,我不认为您的代码正确处理所有数据。例如,如果数据中有逗号或双引号,则需要执行特殊步骤。 Here's some code I published for creating CSV files in C#

答案 1 :(得分:0)

如果您想生成格式化的Excel文档,除了CSV文件或代替它,您还可以查看Excel互操作库。

http://msdn.microsoft.com/en-us/library/bb386107%28v=vs.90%29.aspx

http://support.microsoft.com/kb/301982

http://msdn.microsoft.com/en-us/library/aa188489%28office.10%29.aspx