在.net环境下将报表导出excel和word lihonggen0(原作)
在vb6开发环境下,本人使用excel作过报表,在.net环境下开发,本人使用水晶报表。但vb.net同样可以将报表导出到excel和word进行输出,制作出专业水平的报表。
具体操作如下:(注:首先需添加引用,选择com-->选择microsoft word 10.0 object library和microsoft excel 10.0 object library组件)
1.先创建一个datatable,作为数据来源,也可以另将其它的数据源。
private function creatable() as datatable
dim dt as new datatable()
dt.columns.add("列1", gettype(string))
dt.columns.add("列2", gettype(integer))
dt.columns.add("列3", gettype(string))
dt.columns.add("列4", gettype(string))
dim row, row1 as datarow
row = dt.newrow()
row!列1 = "行1"
row!列2 = 1
row!列3 = "d"
row!列4 = "a"
dt.rows.add(row)
row1 = dt.newrow()
row1!列1 = "行2"
row1!列2 = 12
row1!列3 = "b"
row1!列4 = "c"
dt.rows.add(row1)
return dt
end function
2.将表中的内容导出到excel
dim xlapp as new excel.application()
dim xlbook as excel.workbook
dim xlsheet as excel.worksheet
dim rowindex, colindex as integer
rowindex = 1
colindex = 0
xlbook = xlapp.workbooks().add
xlsheet = xlbook.worksheets("sheet1")
dim table as new datatable()
table = creatable()
'将所得到的表的列名,赋值给单元格
dim col as datacolumn
dim row as datarow
for each col in table.columns
colindex = colindex + 1
xlapp.cells(1, colindex) = col.columnname
next
'得到的表所有行,赋值给单元格
for each row in table.rows
rowindex = rowindex + 1
colindex = 0
for each col in table.columns
colindex = colindex + 1
xlapp.cells(rowindex, colindex) = row(col.columnname)
next
next
with xlsheet
.range(.cells(1, 1), .cells(1, colindex)).font.name = "黑体"
'设标题为黑体字
.range(.cells(1, 1), .cells(1, colindex)).font.bold = true
'标题字体加粗
.range(.cells(1, 1), .cells(rowindex, colindex)).borders.linestyle = 1
'设表格边框样式
end with
with xlsheet.pagesetup
.leftheader = "" & chr(10) & "&""楷体_gb2312,常规""&10公司名称:" ' & gsmc
.centerheader = "&""楷体_gb2312,常规""公司人员情况表&""宋体,常规""" & chr(10) & "&""楷体_gb2312,常规""&10日 期:"
.rightheader = "" & chr(10) & "&""楷体_gb2312,常规""&10单位:"
.leftfooter = "&""楷体_gb2312,常规""&10制表人:"
.centerfooter = "&""楷体_gb2312,常规""&10制表日期:"
.rightfooter = "&""楷体_gb2312,常规""&10第&p页 共&n页"
end with
xlapp.visible = true
3.将表中的内容导出到word
dim wordapp as new word.application()
dim mydoc as word.document
dim otable as word.table
dim rowindex, colindex as integer
rowindex = 1
colindex = 0
wordapp.documents.add()
mydoc = wordapp.activedocument
dim table as new datatable()
table = creatable()
otable = mydoc.tables.add(range:=mydoc.range(start:=0, end:=0), numrows:=table.rows.count + 1, numcolumns:=table.columns.count)
'将所得到的表的列名,赋值给单元格
dim col as datacolumn
dim row as datarow
for each col in table.columns
colindex = colindex + 1
otable.cell(1, colindex).range.insertafter(col.columnname)
next
'得到的表所有行,赋值给单元格
for each row in table.rows
rowindex = rowindex + 1
colindex = 0
for each col in table.columns
colindex = colindex + 1
otable.cell(rowindex, colindex).range.insertafter(row(col.columnname))
next
next
otable.borders.insidelinestyle = 1
otable.borders.outsidelinestyle = 1
wordapp.visible = true
总结:
e_mail:[email protected]