我想将选定的datagridview行中的值导出为MS Word,而不是表格。下面的代码正在运行,但是导出为表格格式。 请帮忙。谢谢!
Private Sub BtnWord_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnWord.Click
Try
'Private Sub BtnWord_Click(ByVal ParcelsDataGridView As DataGridView, ByVal filename As String)
Dim objWord As Word.Application
Dim objDoc As Word.Document
objWord = CreateObject("Word.Application")
objWord.Visible = True
objDoc = objWord.Documents.Add
Dim _RowCount As Integer = ParcelsDataGridView.Rows.Count - 1
Dim _ColCount As Integer = ParcelsDataGridView.Columns.Count - 1
Dim ht1 As Word.Table
ht1 = objDoc.Tables.Add(objDoc.Bookmarks.Item("\endofdoc").Range, _
_RowCount + 1, _ColCount + 1)
ht1.Borders.OutsideColor = Word.WdColor.wdColorBlack
ht1.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
ht1.Borders.InsideColor = Word.WdColor.wdColorBlack
ht1.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
For i As Integer = 0 To _RowCount
ht1.Rows.Add()
For _col As Integer = 0 To _ColCount
Dim colType As Type = ParcelsDataGridView.Columns(_col).GetType
If colType.Name = "DataGridViewImageColumn" Then
Dim _image As Image = DirectCast(ParcelsDataGridView.Rows(i).Cells(_col).Value, Image)
Clipboard.SetImage(_image)
ht1.Cell(i + 1, _col + 1).Range.Paste()
Else
ht1.Cell(i + 1, _col + 1).Range.Text = _
ParcelsDataGridView.Rows(i).Cells(_col).Value.ToString()
End If
Next
Next
objDoc.SaveAs2("C:/test.docx")
Catch ex As System.Exception
MsgBox(ex.Message)
End Try
答案 0 :(得分:0)
您需要进行一些谷歌搜索,以了解Word对象模型的工作原理,尤其是Range
对象。
插入文字的方法如下:
Dim r As Word.Range = d.Content
r.InsertAfter("My heading: ")
r.Bold = 1
r.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
r.InsertAfter("my field value")
r.Bold = 0
r.InsertParagraphAfter()
r.Collapse(Word.WdCollapseDirection.wdCollapseEnd)