简单输出

本节提供了一段示例代码,演示了如何以Word格式输出一个数据表,为方便大家理解,我给每一行代码都加上了注释。

打开CaseStudy目录下的文件"基本功能演示.Table",然后在命令窗口执行下面的代码:

Dim dtab As Table = Tables("订单")
Dim
cols() As String = {"产品", "客户", "单价", "数量", "折扣", "金额", "日期"} '定义要输出的列
Dim
widths() As Double = {50, 50, 50, 60, 60, 77, 120} '定义列宽
Dim
wdc As New WordCreator()
Dim
wtb As New Word.Objects.RtfTable(dtab.Rows.Count + 1, cols.Length) '定义Word表,因为有一个标题行,所以行数要加1
wdc.Add(wtb)
'将表 格添加到文档中
For
c As Integer = 0 To cols.Length - 1 '设置列标题
  
Dim cell As Word.Objects.RtfCell = wtb.Rows(0).Cells(c) '引用单元格
   
Dim rpg As New Word.Objects.RtfParagraph() '定义一个段落
    rpg.Add(
New Word.Objects.RtfString(cols(c))) '在 段落中增加一个RtfString,内容为列标题
    rpg.Alignment = Word.RtfHorizontalAlignment.Center
'列标题居中
    cell.Width = widths(c)
'设置列宽
    cell.Content.Add(rpg)
'将段落添加到单元格中
    cell.SetRectBorder(Word.RtfBorderStyle.Single, color.DarkGray, 1)
'设置边框
Next
For
r As Integer = 0 To dtab.Rows.Count - 1
   
Dim dr As Row = dtab.Rows(r) '引用订单表的数据行
   
For c As Integer = 0 To cols.Length - 1 '遍历要输出的列
       
Dim cname As String = cols(c) '引用列名
       
If dr.IsNull(cname) Then Continue For '跳过空单元格
       
Dim cell As Word.Objects.RtfCell = wtb.Rows(r + 1).Cells(c) '引用单元格
       
Dim rsr As New Word.Objects.RtfString(dr(cname)) '定义一个RtfString,内容默认为订单表中对应列的内容
       
Dim rpg As New Word.Objects.RtfParagraph() '定义一个段落
        rpg.Add(rsr)
'RtfString添加到段落中
       
Select Case cname
           
Case "单价", "数量", "折扣", "金额" '如果是这几个数值列
                rpg.Alignment = Word.RtfHorizontalAlignment.Right
'则元格内容靠右
               
If cols(c) = "折扣" Then '
                    rsr.Text = Format(dr(cname),
"0.00%") '折扣列用百分比显示
               
Else
                    rsr.Text = Format(dr(cname),
"0.00") '其他数值列保留两位小数
               
End If
           
Case "日期"
                rpg.Alignment = Word.RtfHorizontalAlignment.Right
'日期列内容靠右
                rsr.Text = Format(dr(cname),
"yyyyMMdd") '设置日期格式
       
End Select
        cell.Width = widths(c)
'设置列宽
        cell.Content.Add(rpg)
'将段落添加到单元格中
        cell.SetRectBorder(Word.RtfBorderStyle.Single, color.DarkGray, 1)
'设置边框
   
Next
Next
Dim
fl As String = "c:\temp\test.docx"
wdc.Save(fl)
'保存文件
Process.Start(fl)
'打开文件

生成的文档为:


本页地址:http://www.foxtable.com/webhelp/topics/6041.htm