导出到excel将字符串转换为日期

时间:2012-03-23 18:18:09

标签: asp.net vb.net excel

我拉两个字段并用“ - ”将它们组合在一起。当我导出到excel时,似乎认为该字符串是一个日期并将其从11-11转换为11月11日。我似乎无法弄清楚如何解决这个问题。

我正在将gridview导出到excel中。这个asp.net在VS 2008中使用.net 3.5和vb.net。

    Response.Clear()

    Response.Buffer = True

    'grab filename from filename box
    'if does not exist then do default naming
    Dim filename As String
    If filenameTextBox2.Text <> "" Then
        filename = "attachment;filename=" + filenameTextBox2.Text + ".xls"
    Else
        filename = "attachment;filename=GridViewExport.xls"
    End If

    Response.AddHeader("content-disposition", filename)

    Response.Charset = ""

    Response.ContentType = "application/vnd.ms-excel"



    Dim sw As New IO.StringWriter()

    Dim hw As New HtmlTextWriter(sw)



    GridView1.AllowPaging = False

    GridView1.DataBind()


    'Change the Header Row back to white color

    GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF")



    'Apply style to Individual Cells

    'GridView1.HeaderRow.Cells(0).Style.Add("background-color", "green")

    'GridView1.HeaderRow.Cells(1).Style.Add("background-color", "green")

    'GridView1.HeaderRow.Cells(2).Style.Add("background-color", "green")

    'GridView1.HeaderRow.Cells(3).Style.Add("background-color", "green")



    For i As Integer = 0 To GridView1.Rows.Count - 1

        Dim row As GridViewRow = GridView1.Rows(i)



        'Change Color back to white

        row.BackColor = System.Drawing.Color.White



        'Apply text style to each Row

        row.Attributes.Add("class", "textmode")



        'Apply style to Individual Cells of Alternating Row

        If i Mod 2 <> 0 Then

            'row.Cells(0).Style.Add("background-color", "#C2D69B")

            'row.Cells(1).Style.Add("background-color", "#C2D69B")

            'row.Cells(2).Style.Add("background-color", "#C2D69B")

            'row.Cells(3).Style.Add("background-color", "#C2D69B")

        End If

    Next

    GridView1.RenderControl(hw)



    'style to format numbers to string

    Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>"

    Response.Write(style)

    Response.Output.Write(sw.ToString())

    Response.Flush()

    Response.End()

3 个答案:

答案 0 :(得分:1)

尝试在您的内容之前添加单引号(')。

答案 1 :(得分:0)

这是Excel如何解释数据的问题。我建议您根据需要指定数据类型(通过单元格格式)。当您希望以某种方式格式化日期,或者不希望从正常数据中截断前导零时,您也会遇到此问题。

虽然使用文本开头的'会起作用,但它也会产生其他副作用。

根据您创建Excel文件的方式,将决定如何设置单元格格式。我在EPPlus上取得了很大的成功。

答案 2 :(得分:0)

没有引用你的风格不正常。

更改

Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>"

Dim style As String = "<style>.textmode{mso-number-format:""\@"";}</style>"

这完全适合我。