VB.NET導(dǎo)出數(shù)據(jù)實(shí)現(xiàn)你想要的效果
作者:佚名
VB.NET導(dǎo)出數(shù)據(jù)的實(shí)現(xiàn)可以通過本文介紹的這段代碼來進(jìn)行操作。初學(xué)者可以以此為參考對(duì)象,對(duì)這方面的知識(shí)點(diǎn)進(jìn)行一個(gè)充分的了解。
VB.NET開發(fā)語言為我們平時(shí)的開發(fā)方式帶來了非常的改變。很多時(shí)候可以利用Excel的數(shù)據(jù)透視表導(dǎo)出你想要的報(bào)表格式。那么VB.NET導(dǎo)出數(shù)據(jù)該如何實(shí)現(xiàn)呢?下面的代碼可以從數(shù)據(jù)庫中取出數(shù)據(jù)然后導(dǎo)入Excel。
- Dim excel As Excel.Application
- Dim xBk As Excel._Workbook
- Dim xSt As Excel._Worksheet
- Dim xRange As Excel.Range
- Dim xPivotCache As Excel.
PivotCache- Dim xPivotTable As Excel.
PivotTable- Dim xPivotField As Excel.
PivotField- Dim cnnsr As String, sql
As String- Dim RowFields() As String =
{"", "", ""}- Dim PageFields() As String =
{"", "", "", "", "", ""}- 'SERVER 是服務(wù)器名或服務(wù)器的IP地址
- 'DATABASE 是數(shù)據(jù)庫名
- 'Table 是表名
- Try
開始實(shí)現(xiàn)VB.NET導(dǎo)出數(shù)據(jù)
- cnnsr = "ODBC;DRIVER=SQL
Server;SERVER=" + SERVER- cnnsrcnnsr = cnnsr + ";UID=;
APP=Report Tools;WSID=ReportClient;
DATABASE=" + DATABASE- cnnsrcnnsr = cnnsr + ";
Trusted_Connection=Yes"- excel = New Excel.ApplicationClass
- xBk = excel.Workbooks.Add(True)
- xSt = xBk.ActiveSheet
- xRange = xSt.Range("A4")
- xRange.Select()
開始
- xPivotCache = xBk.PivotCaches
.Add(SourceType:=2)- xPivotCache.Connection = cnnsr
- xPivotCache.CommandType = 2
- sql = "select * from " + Table
- xPivotCache.CommandText = sql
- xPivotTable = xPivotCache.
CreatePivotTable(TableDestination:
="Sheet1!R3C1", TableName:=
"數(shù)據(jù)透視表1", DefaultVersion:=1)
準(zhǔn)備行字段
- RowFields(0) = "字段1"
- RowFields(1) = "字段2"
- RowFields(2) = "字段3"
準(zhǔn)備頁面字段
- PageFields(0) = "字段4"
- PageFields(1) = "字段5"
- PageFields(2) = "字段6"
- PageFields(3) = "字段7"
- PageFields(4) = "字段8"
- PageFields(5) = "字段9"
- xPivotTable.AddFields(RowFields
RowFields:=RowFields, PageFields
PageFields:=PageFields)- xPivotField = xPivotTable.
PivotFields("數(shù)量")- xPivotField.Orientation = 4
關(guān)閉工具條
- 'xBk.ShowPivotTableFieldList
= False- 'excel.CommandBars("PivotTable")
.visible = False- excel.Visible = True
- Catch ex As Exception
- If cnn.State = ConnectionState
.Open Then- cnn.Close()
- End If
- xBk.Close(0)
- excel.Quit()
- MessageBox.Show(ex.Message,
"報(bào)表工具", MessageBoxButtons.
OK, MessageBoxIcon.Warning)- End Try
VB.NET導(dǎo)出數(shù)據(jù)的具體代碼編寫就為大家介紹到這里。
【編輯推薦】
責(zé)任編輯:曹凱
來源:
IT168