Bài t?ng bư?c này mô t? m?t s? phương pháp cho
chuy?n d? li?u v?i Excel 2002 t? m?t Visual Basic.NET chương tr?nh. Bài vi?t này
c?ng tr?nh bày nh?ng l?i th? và b?t l?i c?a t?ng phương pháp do đó b?n có th?
ch?n gi?i pháp làm vi?c t?t nh?t cho t?nh h?nh c?a b?n.
T?ng quan
Các k? thu?t đư?c s? d?ng thư?ng xuyên nh?t đ? truy?n d? li?u đ?n m?t
B?ng tính Excel là
T? đ?ng hóa. V?i t? đ?ng hóa, b?n có th? g?i phương pháp và các tính năng mà
c? th? cho tác v? này Excel. T? đ?ng hóa giúp b?n linh ho?t l?n nh?t cho
xác đ?nh v? trí c?a d? li?u c?a b?n trong b?ng tính, và kh? năng đ?nh d?ng
b?ng tính và th?c hi?n cài đ?t khác nhau t?i th?i gian ch?y.
V?i t? đ?ng hóa,
b?n có th? s? d?ng m?t s? k? thu?t đ? truy?n d? li?u c?a b?n:
- Chuy?n d? li?u di đ?ng c?a t? bào.
- Chuy?n d? li?u trong m?t m?ng đ?n m?t lo?t các t? bào.
- Chuy?n d? li?u trong m?t recordset ADO đ?n m?t lo?t các t? bào b?i
b?ng cách s? d?ng các CopyFromRecordset phương pháp.
- T?o ra m?t QueryTable đ?i tư?ng vào m?t b?ng tính Excel có ch?a các k?t qu? c?a m?t truy v?n
trên m?t ODBC ho?c OLEDB ngu?n d? li?u.
- Chuy?n d? li?u vào b?ng t?m, và sau đó dán các
n?i dung b?ng t?m vào m?t b?ng tính Excel.
B?n c?ng có th? s? d?ng m?t s? phương pháp mà làm không nh?t thi?t ph?i
yêu c?u t? đ?ng hóa đ? truy?n d? li?u v?i Excel. N?u b?n đang ch?y m?t phía máy ch?
chương tr?nh, đi?u này có th? là m?t cách ti?p c?n t?t đ? dành ph?n l?n c?a x? l? d? li?u
t? khách hàng c?a b?n.
Các phương pháp sau đây có th? đư?c s? d?ng đ?
chuy?n d? li?u c?a b?n mà không có t? đ?ng hóa:
- Chuy?n d? li?u c?a b?n vào m?t tab ho?c d?u ph?y phân cách t?p tin văn b?n
r?ng Excel có th? sau đó phân tích vào các t? bào trên m?t b?ng tính.
- Chuy?n d? li?u vào m?t b?ng tính b?ng cách s? d?ng ADO.NET.
- Chuy?n d? li?u XML đ? Excel (Phiên b?n 2002 ch?) đ? cung c?p
d? li?u đó là đ?nh d?ng và s?p x?p thành các hàng và c?t.
K? thu?t
S? d?ng t? đ?ng hóa đ? truy?n d? li?u di đ?ng c?a t? bào
V?i t? đ?ng hóa, b?n có th? chuy?n d? li?u vào m?t b?ng tính m?t cell lúc
m?t th?i gian, như sau.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel.
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
'Add data to cells of the first worksheet in the new workbook.
oSheet = oBook.Worksheets(1)
oSheet.Range("A1").Value = "Last Name"
oSheet.Range("B1").Value = "First Name"
oSheet.Range("A1:B1").Font.Bold = True
oSheet.Range("A2").Value = "Doe"
oSheet.Range("B2").Value = "John"
'Save the Workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book1.xls")
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
Chuy?n d? li?u di đ?ng c?a t? bào có th? là m?t cách ti?p c?n ch?p nh?n đư?c n?u có
không ph?i là nhi?u d? li?u đ? chuy?n. B?n có s? linh ho?t đ? đ?t d? li?u ? b?t c? đâu trong
b?ng tính và có th? đ?nh d?ng các t? bào có đi?u ki?n và th?i gian ch?y. Tuy nhiên, đi?u này
cách ti?p c?n không đư?c khuy?n khích n?u b?n có r?t nhi?u d? li?u đ? chuy?n giao cho m?t Excel
b?ng tính. M?i
Ph?m vi đ?i tư?ng mà b?n có đư?c t?i th?i gian ch?y k?t qu? trong m?t giao di?n
yêu c?u. V? v?y, chuy?n giao d? li?u theo cách này có th? đư?c làm ch?m.
Ngoài ra,
Microsoft Windows 95, Microsoft Windows 98 và Microsoft Windows Millennium
?n b?n (tôi) có m?t gi?i h?n 64 KB trên yêu c?u giao di?n. N?u b?n có 64 KB
ho?c nhi?u hơn giao di?n yêu c?u, các máy ch? t? đ?ng hóa (Excel) có th? ng?ng
đáp ?ng, ho?c b?n có th? nh?n các thông báo l?i ch? ra thi?u b? nh?. Đ? bi?t thêm chi ti?t, nh?p vào s? bài vi?t sau đây đ? xem bài vi?t trong cơ s? ki?n th?c Microsoft:
216400
(http://support.microsoft.com/kb/216400/
)
T? đ?ng hóa COM Cross, quá tr?nh có th? treo ?ng d?ng khách trên Win95/98
M?t l?n n?a, chuy?n giao d? li?u di đ?ng c?a t? bào đư?c ch?p nh?n
ch? cho m?t lư?ng nh? d? li?u. N?u b?n ph?i chuy?n d? li?u l?n đ?t cho Excel,
nên s? d?ng m?t cách ti?p c?n khác đang th?o lu?n trong bài vi?t này
đ? truy?n d? li?u v?i s? lư?ng l?n.
Cho bi?t thêm thông tin, và cho m?t ví d? v? làm th? nào đ? t? đ?ng hoá Excel
v?i Visual Basic.NET, nh?p vào s? bài vi?t sau đây đ? xem bài vi?t trong cơ s? ki?n th?c Microsoft:
301982
(http://support.microsoft.com/kb/301982/
)
Làm th? nào đ? t? đ?ng hoá Microsoft Excel t? Visual Basic.NET
S? d?ng t? đ?ng hóa đ? chuy?n m?t m?ng c?a d? li?u đ?n m?t ph?m vi ngày m?t b?ng
M?t m?ng c?a d? li?u có th? đư?c chuy?n giao cho m?t lo?t các t? bào nhi?u
đ?ng th?i, như sau.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel.
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
'Create an array with 3 columns and 100 rows.
Dim DataArray(99, 2) As Object
Dim r As Integer
For r = 0 To 99
DataArray(r, 0) = "ORD" & Format(r + 1, "0000")
DataArray(r, 1) = Rnd() * 1000
DataArray(r, 2) = DataArray(r, 1) * 0.07
Next
'Add headers to the worksheet on row 1.
oSheet = oBook.Worksheets(1)
oSheet.Range("A1").Value = "Order ID"
oSheet.Range("B1").Value = "Amount"
oSheet.Range("C1").Value = "Tax"
'Transfer the array to the worksheet starting at cell A2.
oSheet.Range("A2").Resize(100, 3).Value = DataArray
'Save the Workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book2.xls")
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
N?u b?n chuy?n d? li?u b?ng cách s? d?ng m?t m?ng thay v? c?a t? bào c?a ô,
b?n có th? nh?n ra m?t đ?t đư?c hi?u su?t r?t l?n v?i nhi?u d? li?u. Xem xét vi?c này
d?ng t? m? s? trư?c đó truy?n d? li?u đ?n các t? bào 300 trong b?ng tính.
oSheet.Range("A2").Resize(100, 3).Value = DataArray
D?ng này đ?i di?n cho hai giao di?n yêu c?u: m?t cho các
Ph?m vi đ?i tư?ng mà các
Ph?m vi tr? v? phương pháp, và m?t cho các
Ph?m vi đ?i tư?ng mà các
Thay đ?i kích c? phương pháp tr? v?. Ngư?c l?i, chuy?n giao d? li?u di đ?ng c?a t? bào
đ?i h?i yêu c?u cho giao di?n 300 đ?
Ph?m vi các đ?i tư?ng. B?t c? khi nào có th?, b?n có th? hư?ng l?i t? chuy?n
d? li?u c?a b?n v?i s? lư?ng l?n và vi?c gi?m s? lư?ng yêu c?u giao di?n b?n th?c hi?n.
S? d?ng t? đ?ng hóa đ? chuy?n m?t recordset ADO đ?n m?t lo?t các b?ng tính
Các mô h?nh đ?i tư?ng cho Excel 2000 và Excel 2002 cung c?p các
CopyFromRecordset phương th?c đ? chuy?n m?t recordset ADO đ?n m?t ph?m vi ngày m?t
b?ng tính. Các m? sau đây minh ho? làm th? nào đ? t? đ?ng hoá Excel đ? chuy?n các
n?i dung c?a b?ng đơn đ?t hàng m?u Northwind cơ s? d? li?u b?ng cách s? d?ng các
CopyFromRecordset phương pháp.
'Create a Recordset from all the records in the Orders table.
Dim sNWind As String
Dim conn As New ADODB.Connection()
Dim rs As ADODB.Recordset
conn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
sNorthwind & ";")
conn.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs = conn.Execute("Orders", , ADODB.CommandTypeEnum.adCmdTable)
'Create a new workbook in Excel.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
'Transfer the field names to Row 1 of the worksheet:
'Note: CopyFromRecordset copies only the data and not the field
' names, so you can transfer the fieldnames by traversing the
' fields collection.
Dim n As Int32
For n = 1 To rs.Fields.Count
oSheet.Cells(1, n).Value = rs.Fields(n - 1).Name
Next
'Transfer the data to Excel.
oSheet.Range("A2").CopyFromRecordset(rs)
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book3.xls")
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
'Close the connection
rs.Close()
conn.Close()
Lưu ? CopyFromRecordset tác ph?m ch? v?i ADO
RecordSet các đ?i tư?ng. A
S? li?u r?ng b?n t?o b?ng cách s? d?ng ADO.NET không th? đư?c s? d?ng v?i các
CopyFromRecordset phương pháp. M?t vài ví d? trong các ph?n theo sau ch?ng minh
làm th? nào đ? truy?n d? li?u v?i Excel v?i ADO.NET.
S? d?ng t? đ?ng hóa đ? t?o ra m?t đ?i tư?ng QueryTable trên m?t b?ng
A
QueryTable đ?i tư?ng đ?i di?n cho m?t b?ng đư?c xây d?ng t? d? li?u
tr? v? t? m?t ngu?n d? li?u bên ngoài. Trong khi b?n t? đ?ng Excel, b?n có th? t?o
m?t
QueryTable b?ng cách cung c?p m?t chu?i k?t n?i đ?n m?t OLEDB ho?c m?t d? li?u ODBC
ngu?n và m?t chu?i SQL. Excel t?o ra recordset và chèn các
RecordSet vào b?ng tính ? v? trí mà b?n ch? đ?nh. B?ng cách s? d?ng
QueryTable các đ?i tư?ng cung c?p nh?ng ưu đi?m sau hơn các
CopyFromRecordset phương pháp:
- Excel x? l? vi?c t?o ra recordset và c?a nó
v? trí vào b?ng tính.
- Truy v?n có th? đư?c lưu v?i các QueryTable đ?i tư?ng như v?y là nó có th? đư?c làm m?i l?n sau đó đ? có đư?c m?t C?p Nh?t
RecordSet.
- Khi tin nhaén QueryTable s? đư?c thêm vào b?ng tính c?a b?n, b?n có th? ch? ra r?ng d? li?u đ?
hi?n có trong các t? bào trên b?ng tính đư?c d?ch chuy?n đ? phù h?p v?i các d? li?u m?i (xem các RefreshStyle b?t đ?ng s?n đ? bi?t chi ti?t).
Các m? sau đây ch?ng t? làm th? nào đ? t? đ?ng hoá Excel 2000 ho?c
năm 2002 đ? t?o ra m?t m?i
QueryTable trong m?t b?ng tính Excel b?ng cách s? d?ng d? li?u t? m?u Northwind
cơ s? d? li?u.
'Create a new workbook in Excel.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
'Create the QueryTable object.
Dim oQryTable As Object
oQryTable = oSheet.QueryTables.Add( _
"OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
sNorthwind & ";", oSheet.Range("A1"), _
"Select * from Orders")
oQryTable.RefreshStyle = 2 ' xlInsertEntireRows = 2
oQryTable.Refresh(False)
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book4.xls")
oQryTable = Nothing
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
S? d?ng b?ng t?m
B?n có th? s? d?ng b?ng t?m đ? truy?n d? li?u đ?n m?t
b?ng tính. Đ? dán d? li?u vào các t? bào nhi?u trên m?t b?ng, b?n có th? sao chép m?t
chu?i trong đó c?t đư?c phân cách b?i các tab nhân v?t, và các hàng đư?c phân cách
b?i v?n chuy?n tr? v?. Đo?n m? sau minh ho? cách Visual Basic.S? d?ng NET
B?ng t?m đ? truy?n d? li?u v?i Excel.
'Copy a string to the Clipboard.
Dim sData As String
sData = "FirstName" & vbTab & "LastName" & vbTab & "Birthdate" & vbCr _
& "Bill" & vbTab & "Brown" & vbTab & "2/5/85" & vbCr _
& "Joe" & vbTab & "Thomas" & vbTab & "1/1/91"
System.Windows.Forms.Clipboard.SetDataObject(sData)
'Create a workbook in Excel.
Dim oExcel As Object
Dim oBook As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
'Paste the data.
oBook.Worksheets(1).Range("A1").Select()
oBook.Worksheets(1).Paste()
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book5.xls")
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
T?o m?t t?p tin văn b?n delimited Excel có th? phân tích cú pháp thành các hàng và c?t
Excel có th? m? tab-phân cách t?p tin ho?c d?u ph?y phân cách t?p tin và phân tích m?t cách chính xác
các d? li?u vào các t? bào. B?n có th? s? d?ng tính năng này khi b?n mu?n chuy?n r?t nhi?u
d? li?u vào m?t b?ng tính trong khi s? d?ng ít, n?u có, t? đ?ng hóa. Đây có th? là m?t
cách ti?p c?n t?t cho m?t khách hàng máy ch? chương tr?nh, b?i v? các t?p tin văn b?n có th?
t?o ra phía máy ch?. B?n có th? sau đó, m? t?p tin văn b?n t?i khách hàng, s? d?ng
T? đ?ng hóa mà nó là thích h?p.
Các m? sau đây minh ho?
làm th? nào đ? t?o ra m?t tab-delimited text file t? d? li?u đư?c đ?c v?i ADO.NET.
'Connect to the data source.
Dim objConn As New System.Data.OleDb.OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sNorthwind & ";")
objConn.Open()
'Execute a command to retrieve all records from the Employees table.
Dim objCmd As New System.Data.OleDb.OleDbCommand( _
"Select * From Employees", objConn)
Dim objReader As System.Data.OleDb.OleDbDataReader
objReader = objCmd.ExecuteReader()
'Read the records in the dataset and write select fields to the
'output file.
FileOpen(1, sSampleFolder & "Book6.txt", OpenMode.Output)
Dim i As Integer, s As String
While objReader.Read()
'Loop through first 6 fields and concatenate
'each field, separated by a tab, into s variable.
s = ""
For i = 0 To 5
If Not objReader.IsDBNull(i) Then
If i = 0 Then 'field 1 is EmployeeId
s = s & objReader.GetInt32(i).ToString
ElseIf i = 5 Then 'field 6 is BirthDate
s = s & objReader.GetDateTime(i)
Else 'field is a text field
s = s & objReader.GetString(i)
End If
End If
s = s & Microsoft.VisualBasic.ControlChars.Tab
Next
PrintLine(1, s)
End While
FileClose(1)
'Close the reader and the connection.
objReader.Close()
objConn.Close()
Không có t? đ?ng hóa đư?c s? d?ng trong m? trư?c đó. Tuy nhiên, b?n có th? s? d?ng
t? đ?ng hóa t?i thi?u đ? m? t?p tin văn b?n và lưu các t?p tin trong Excel
b?ng tính đ?nh d?ng, như sau.
'Create a new instance of Excel.
Dim oExcel As Object
oExcel = CreateObject("Excel.Application")
'Open the text file and save it in the Excel workbook format.
oExcel.Workbooks.OpenText(sSampleFolder & "Book6.txt", _
, , , -4142, , True) 'xlTextQualifierNone=-4142
oExcel.ActiveWorkbook.SaveAs(sSampleFolder & "Book6.xls", _
-4143) 'xlWorkbookNormal = -4143
'Quit Excel.
oExcel.Quit()
oExcel = Nothing
GC.Collect()
Chuy?n d? li?u vào m?t b?ng tính b?ng cách s? d?ng ADO.NET
B?n có th? s? d?ng các nhà cung c?p c?a Microsoft ph?n l?c OLE DB thêm h? sơ đ?n m?t
b?ng trong m?t b?ng tính Excel hi?n có. M?t b?ng"" trong Excel là ch? đơn thu?n là m?t lo?t các
các t? bào; ph?m vi có th? có m?t tên đư?c xác đ?nh. Thông thư?ng, hàng đ?u c?a d?y
ch?a các tiêu đ? (ho?c l?nh v?c tên), và sau đó t?t c? các hàng trong ph?m vi ch?a
các h? sơ.
Các m? sau đây cho bi?t thêm hai m?i ghi m?t b?ng ?
Book7.xls. các b?ng trong trư?ng h?p này là Sheet1.
'Establish a connection to the data source.
Dim sConnectionString As String
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sSampleFolder & _
"Book7.xls;Extended Properties=Excel 8.0;"
Dim objConn As New System.Data.OleDb.OleDbConnection(sConnectionString)
objConn.Open()
'Add two records to the table.
Dim objCmd As New System.Data.OleDb.OleDbCommand()
objCmd.Connection = objConn
objCmd.CommandText = "Insert into [Sheet1$] (FirstName, LastName)" & _
" values ('Bill', 'Brown')"
objCmd.ExecuteNonQuery()
objCmd.CommandText = "Insert into [Sheet1$] (FirstName, LastName)" & _
" values ('Joe', 'Thomas')"
objCmd.ExecuteNonQuery()
'Close the connection.
objConn.Close()
Khi b?n thêm h? sơ v?i ADO.NET như đư?c hi?n th?, đ?nh d?ng trong các
b?ng tính đư?c duy tr?. M?i b?n ghi s? đư?c thêm vào m?t hàng vay mư?n các đ?nh d?ng
t? hàng trư?c khi nó. Ví d?, các l?nh v?c m?i đư?c b? sung vào c?t B
đ?nh d?ng v?i quy?n ch?nh v? ô B1 là quy?n liên k?t.
Lưu ? r?ng khi m?t b?n ghi đư?c đưa vào m?t t? bào ho?c các t? bào trong b?ng tính, nó
ghi đè b?t k? d? li?u nào nh?ng t? bào trư?c đây ch?a. Nói cách khác, các hàng
trong b?ng tính không "đ?y" khi h? sơ m?i đư?c thêm vào. Gi? đi?u này trong
nh? khi b?n thi?t k? b? trí d? li?u trên b?ng c?a b?n n?u b?n có k? ho?ch các
Chèn m?i ghi b?ng cách s? d?ng ADO.NET.
Đ? bi?t thêm v? cách s? d?ng
ADO.NET, nh?p vào s? bài vi?t sau đ? xem các bài vi?t trong cơ s? ki?n th?c Microsoft:
301075
(http://support.microsoft.com/kb/301075/
)
Làm th? nào đ? k?t n?i v?i cơ s? d? li?u và ch?y m?t l?nh b?ng cách s? d?ng ADO.NET và Visual Basic.NET
301216
(http://support.microsoft.com/kb/301216/
)
Làm th? nào đ? cư trú m?t đ?i tư?ng t?p d? li?u t? cơ s? d? li?u b?ng cách s? d?ng Visual Basic.NET
301248
(http://support.microsoft.com/kb/301248/
)
Làm th? nào đ? c?p nh?t cơ s? d? li?u t? m?t đ?i tư?ng t?p d? li?u b?ng cách s? d?ng Visual Basic.NET
Đ? bi?t thêm v? cách s? d?ng các nhà cung c?p máy bay ph?n l?c OLE DB v?i
Excel ngu?n d? li?u, b?m s? bài vi?t sau đây đ? xem bài vi?t trong cơ s? ki?n th?c Microsoft:
278973
(http://support.microsoft.com/kb/278973/
)
ExcelADO ch?ng t? làm th? nào đ? s? d?ng ADO đ? đ?c và ghi d? li?u trong Excel Workbook
257819
(http://support.microsoft.com/kb/257819/
)
Làm th? nào đ? s? d?ng ADO v?i d? li?u Excel t? Visual Basic ho?c VBA
Chuy?n d? li?u XML (Excel 2002 ch?)
Excel 2002 có th? m? b?t k? t?p tin XML là t?t đư?c h?nh thành. T?p tin XML
có th? đư?c m? tr?c ti?p t? các
M? l?nh trên các
T?p tin tr?nh đơn, ho?c l?p tr?nh b?ng cách s? d?ng m?t trong hai các
M? ho?c
OpenXML phương pháp c?a các
Sách bài t?p b? sưu t?p. N?u b?n t?o t?p tin XML đ? s? d?ng trong Excel, b?n có th?
c?ng t?o phong cách trang tính đ?nh d?ng d? li?u.
Đ? bi?t thêm thông tin v? cách s? d?ng XML
v?i Excel 2002, nh?p vào s? bài vi?t sau đ? xem các bài vi?t trong cơ s? ki?n th?c Microsoft:
307021
(http://support.microsoft.com/kb/307021/
)
Làm th? nào đ? chuy?n d? li?u XML đ? Microsoft Excel 2002 b?ng cách s? d?ng Visual Basic.NET
288215
(http://support.microsoft.com/kb/288215/
)
Microsoft Excel 2002 và XML
T?o hoàn ch?nh m?u Visual Basic.LƯ?I d? án
- T?o m?t thư m?c m?i đ? gi? Excel Workbook mà các
m?u s? t?o cho b?n, và sau đó tên thư m?c C:\Exceldata\.
- Làm theo các bư?c sau đ? t?o ra m?t b?ng tính m?i cho m?u
đ? vi?t thư cho:
- B?t đ?u m?t b?ng tính m?i trong Excel.
- Ngày Sheet1 c?a b?ng tính m?i, h?y g? FirstName trong cell A1 và Th?trong t? bào A2.
- Lưu b?ng tính như C:\Exceldata\Book7.xls.
- B?t đ?u Visual Studio.NET. Trên các T?p tin tr?nh đơn, nh?p vào M?i sau đó b?m D? án. Dư?i Visual Basic d? án, ch?n ?ng d?ng Windows. Theo m?c đ?nh, Form1 đư?c t?o ra.
- Thêm m?t tham chi?u đ?n các thư vi?n đ?i tư?ng Excel. Đ? làm đi?u này,
th?c hi?n theo các bư?c sau:
- Trên các D? án tr?nh đơn, nh?p vào Thêm tài li?u tham kh?o.
- Trên các COM tab, xác đ?nh v? trí Microsoft Excel 10,0 đ?i tư?ng thư vi?n, sau đó b?m Ch?n.
Lưu ? N?u b?n không làm như v?y, Microsoft khuy?n cáo r?ng b?n
t?i v? và sau đó cài đ?t Microsoft Office XP chính Interop h?i đ?ng
(PIAs). Đ? bi?t thêm chi ti?t v? Office XP PIAs, nh?p vào s? bài vi?t sau đây đ? xem bài vi?t trong cơ s? ki?n th?c Microsoft:328912
(http://support.microsoft.com/kb/328912/
)
Microsoft Office XP chính interop h?i đ?ng (PIAs) có s?n đ? t?i v?
- Trên các COM tab, xác đ?nh v? trí Microsoft ActiveX Data Objects 2,7 Library, sau đó b?m Ch?n.
- Nh?p vào Ok trong các Thêm tài li?u tham kh?o h?p tho?i đ? ch?p nh?n c?a b?n l?a ch?n. N?u b?n nh?n đư?c m?t nh?c đ?n
t?o ra hàm bao cho các thư vi?n mà b?n đ? ch?n, b?m vào Có.
- Thêm m?t H?p combo ki?m soát và m?t Nút ki?m soát đ? Form1.
- Thêm m? sau đây đ? Form1.
Const sSampleFolder = "C:\ExcelData\"
Const sNorthwind = "C:\Program Files\Microsoft Office\Office10\Samples\Northwind.mdb"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Load
ComboBox1.DropDownStyle = ComboBoxStyle.DropDownList
Dim aList As String() = _
{"Use Automation to Transfer Data Cell by Cell ", _
"Use Automation to Transfer an Array of Data to a Range on a Worksheet ", _
"Use Automation to Transfer an ADO Recordset to a Worksheet Range ", _
"Use Automation to Create a QueryTable on a Worksheet", _
"Use the Clipboard", _
"Create a Delimited Text File that Excel Can Parse into Rows and Columns", _
"Transfer Data to a Worksheet Using ADO.NET "}
ComboBox1.Items.AddRange(aList)
ComboBox1.SelectedIndex = 0
Button1.Text = "Go!"
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button1.Click
Select Case ComboBox1.SelectedIndex
Case 0 : Automation_CellByCell()
Case 1 : Automation_UseArray()
Case 2 : Automation_ADORecordset()
Case 3 : Automation_QueryTable()
Case 4 : Use_Clipboard()
Case 5 : Create_TextFile()
Case 6 : Use_ADONET()
End Select
GC.Collect()
End Sub
Private Function Automation_CellByCell()
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel.
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
'Add data to cells of the first worksheet in the new workbook.
oSheet = oBook.Worksheets(1)
oSheet.Range("A1").Value = "Last Name"
oSheet.Range("B1").Value = "First Name"
oSheet.Range("A1:B1").Font.Bold = True
oSheet.Range("A2").Value = "Doe"
oSheet.Range("B2").Value = "John"
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book1.xls")
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
End Function
Private Function Automation_UseArray()
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel.
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
'Create an array with 3 columns and 100 rows.
Dim DataArray(99, 2) As Object
Dim r As Integer
For r = 0 To 99
DataArray(r, 0) = "ORD" & Format(r + 1, "0000")
DataArray(r, 1) = Rnd() * 1000
DataArray(r, 2) = DataArray(r, 1) * 0.07
Next
'Add headers to the worksheet on row 1.
oSheet = oBook.Worksheets(1)
oSheet.Range("A1").Value = "Order ID"
oSheet.Range("B1").Value = "Amount"
oSheet.Range("C1").Value = "Tax"
'Transfer the array to the worksheet starting at cell A2.
oSheet.Range("A2").Resize(100, 3).Value = DataArray
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book2.xls")
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
End Function
Private Function Automation_ADORecordset()
'Create a Recordset from all the records in the Orders table.
Dim sNWind As String
Dim conn As New ADODB.Connection()
Dim rs As ADODB.Recordset
conn.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
sNorthwind & ";")
conn.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs = conn.Execute("Orders", , ADODB.CommandTypeEnum.adCmdTable)
'Create a new workbook in Excel.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
'Transfer the field names to Row 1 of the worksheet:
'Note: CopyFromRecordset copies only the data and not the field
' names, so you can transfer the fieldnames by traversing the
' fields collection.
Dim n As Int32
For n = 1 To rs.Fields.Count
oSheet.Cells(1, n).Value = rs.Fields(n - 1).Name
Next
'Transfer the data to Excel.
oSheet.Range("A2").CopyFromRecordset(rs)
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book3.xls")
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
'Close the connection.
rs.Close()
conn.Close()
End Function
Private Function Automation_QueryTable()
'Create a new workbook in Excel.
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
'Create the QueryTable object.
Dim oQryTable As Object
oQryTable = oSheet.QueryTables.Add( _
"OLEDB;Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
sNorthwind & ";", oSheet.Range("A1"), _
"Select * from Orders")
oQryTable.RefreshStyle = 2 ' xlInsertEntireRows = 2
oQryTable.Refresh(False)
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book4.xls")
oQryTable = Nothing
oSheet = Nothing
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
End Function
Private Function Use_Clipboard()
'Copy a string to the clipboard.
Dim sData As String
sData = "FirstName" & vbTab & "LastName" & vbTab & "Birthdate" & vbCr _
& "Bill" & vbTab & "Brown" & vbTab & "2/5/85" & vbCr _
& "Joe" & vbTab & "Thomas" & vbTab & "1/1/91"
System.Windows.Forms.Clipboard.SetDataObject(sData)
'Create a new workbook in Excel.
Dim oExcel As Object
Dim oBook As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
'Paste the data.
oBook.Worksheets(1).Range("A1").Select()
oBook.Worksheets(1).Paste()
'Save the workbook and quit Excel.
oBook.SaveAs(sSampleFolder & "Book5.xls")
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
GC.Collect()
End Function
Private Function Create_TextFile()
'Connect to the data source.
Dim objConn As New System.Data.OleDb.OleDbConnection( _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sNorthwind & ";")
objConn.Open()
'Run a command to retrieve all records from the Employees table.
Dim objCmd As New System.Data.OleDb.OleDbCommand( _
"Select * From Employees", objConn)
Dim objReader As System.Data.OleDb.OleDbDataReader
objReader = objCmd.ExecuteReader()
'Read the records in the dataset and write select fields to the
'output file.
FileOpen(1, sSampleFolder & "Book6.txt", OpenMode.Output)
Dim i As Integer, s As String
While objReader.Read()
'Loop through first 6 fields and concatenate
'each field, separated by a tab, into s variable.
s = ""
For i = 0 To 5
If Not objReader.IsDBNull(i) Then
If i = 0 Then 'field 1 is EmployeeId
s = s & objReader.GetInt32(i).ToString
ElseIf i = 5 Then 'field 6 is BirthDate
s = s & objReader.GetDateTime(i)
Else 'field is a text field
s = s & objReader.GetString(i)
End If
End If
s = s & Microsoft.VisualBasic.ControlChars.Tab
Next
PrintLine(1, s)
End While
FileClose(1)
'Close the reader and the connection.
objReader.Close()
objConn.Close()
'Create a new instance of Excel.
Dim oExcel As Object
oExcel = CreateObject("Excel.Application")
'Open the text file and save it in the Excel workbook format.
oExcel.Workbooks.OpenText(sSampleFolder & "Book6.txt", _
, , , -4142, , True) 'xlTextQualifierNone=-4142
oExcel.ActiveWorkbook.SaveAs(sSampleFolder & "Book6.xls", _
-4143) 'xlWorkbookNormal = -4143
'Quit Excel.
oExcel.Quit()
oExcel = Nothing
GC.Collect()
End Function
Private Function Use_ADONET()
'Verify that the workbook to write to does exist.
Dim sFile As String = sSampleFolder & "Book7.xls"
If Dir(sFile) = "" Then
MsgBox("Please create the workbook Book7.xls and try again.")
Exit Function
End If
'Establish a connection to the data source.
Dim sConnectionString As String
sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sSampleFolder & _
"Book7.xls;Extended Properties=Excel 8.0;"
Dim objConn As New System.Data.OleDb.OleDbConnection(sConnectionString)
objConn.Open()
'Add two records to the table named 'MyTable'.
Dim objCmd As New System.Data.OleDb.OleDbCommand()
objCmd.Connection = objConn
objCmd.CommandText = "Insert into [Sheet1$] (FirstName, LastName)" & _
" values ('Bill', 'Brown')"
objCmd.ExecuteNonQuery()
objCmd.CommandText = "Insert into [Sheet1$] (FirstName, LastName)" & _
" values ('Joe', 'Thomas')"
objCmd.ExecuteNonQuery()
'Close the connection.
objConn.Close()
End Function
Lưu ? N?u b?n không cài đ?t văn ph?ng thư m?c m?c đ?nh (c: Program Files
Microsoft Office), thay đ?i các sNorthwind h?ng s? trong m?u m? đ? phù h?p v?i đư?ng d?n cài đ?t c?a b?n cho
Northwind.mdb.
- Thêm m? sau vào phía trên c?a Form1.vb.
Imports Microsoft.Office.Interop
- Nh?n F5 đ? xây d?ng và sau đó ch?y các m?u.