-1

在我的项目中,我正在创建一个 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

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

在此处输入图像描述

4

2 回答 2

2

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

此外,我认为您的代码无法正确处理所有数据。例如,如果数据中有逗号或双引号,则需要特殊步骤。这是我发布的一些代码,用于在 C# 中创建 CSV 文件

于 2012-04-18T05:13:02.823 回答
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

于 2012-04-18T10:46:54.767 回答