vb.net-将gridview导出到word

时间:2018-07-05 15:26:10

标签: .net vb.net

我正在使用以下代码将gridview导出到Microsoft word上:

        Response.Clear()
        Response.Buffer = True
        Response.AddHeader("content-disposition", "attachment;filename=" & CountryName & ".doc")
        Response.Charset = ""
        Response.ContentType = "application/vnd.ms-word "
        Dim sw As StringWriter = New StringWriter()
        Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
        gridview1.AllowPaging = False
        gridview1.DataBind()
        gridview1.RenderControl(hw)
        Response.Output.Write(sw.ToString())
        Response.Flush()
        Response.[End]()

是否可以格式化文档?例如因为它是一个gridview,它也导出表行,是否有摆脱它的方法?和其他格式

感谢帮助

1 个答案:

答案 0 :(得分:0)

尝试此操作可能会对您有所帮助。

这是一个示例方法。在这里,您可以找到如何将DataGridView导出到Word和Excel文档中。

Private Sub btnWord_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim sfd As SaveFileDialog = New SaveFileDialog()
    sfd.Filter = "Word Documents (*.doc)|*.doc"
    sfd.FileName = "export.doc"

    If sfd.ShowDialog() = DialogResult.OK Then
        ToCsV(dataGridView1, sfd.FileName)
    End If
End Sub

Private Sub ToCsV(ByVal dGV As DataGridView, ByVal filename As String)
    Dim stOutput As String = ""
    Dim sHeaders As String = ""

    For j As Integer = 0 To dGV.Columns.Count - 1
        sHeaders = sHeaders.ToString() & Convert.ToString(dGV.Columns(j).HeaderText) & vbTab
    Next

    stOutput += sHeaders & vbCrLf

    For i As Integer = 0 To dGV.RowCount - 1 - 1
        Dim stLine As String = ""

        For j As Integer = 0 To dGV.Rows(i).Cells.Count - 1
            stLine = stLine.ToString() & Convert.ToString(dGV.Rows(i).Cells(j).Value) & vbTab
        Next

        stOutput += stLine & vbCrLf
    Next

    Dim utf16 As Encoding = Encoding.GetEncoding(1254)
    Dim output As Byte() = utf16.GetBytes(stOutput)
    Dim fs As FileStream = New FileStream(filename, FileMode.Create)
    Dim bw As BinaryWriter = New BinaryWriter(fs)
    bw.Write(output, 0, output.Length)
    bw.Flush()
    bw.Close()
    fs.Close()
End Sub