簡體   English   中英

vb.net-將gridview導出到word

[英]vb.net - export gridview to word

我正在使用以下代碼將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,它也導出表行,是否有擺脫它的方法? 等格式

感謝幫助

試試這個可能對您有幫助。

這是執行此操作的示例方法。 在這里,您可以找到如何將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM