本文將逐步告訴您,從 Visual Basic.NET 程式傳送資料到 Excel 2002 的幾個方法。本文也提供每個方法的優缺點,這樣您就可以選取最適合您情況的解決方案。
概觀
傳輸資料到 Excel 活頁簿最常使用的技巧會
自動化。使用自動化,您可以呼叫方法和 Excel 任務特有的屬性。自動化可讓您最大的彈性,為在活頁簿和能力格式化活頁簿,並在執行階段進行各種設定中指定您資料的位置。
自動化,您可以使用數種技巧?傳送您的資料:
- 傳輸資料的儲存格。
- 將陣列中的資料傳送至儲存格範圍。
- 將 ADO 資料錄集的資料轉移到某範圍的儲存格,利用 CopyFromRecordset 方法。
- 建立 QueryTable 物件包含了 ODBC 或 OLEDB 資料來源中的查詢結果的 Excel 工作表上。
- 將資料傳送至剪貼簿,然後將剪貼簿內容貼到 Excel 工作表。
您也可以使用數種方法不一定需要傳輸資料到 Excel 的自動化。如果您正在執行伺服器端程式,這可以是拍攝遠離您的用戶端的資料處理大量的一個好方法。
下列方法可以用來傳輸沒有自動化您資料:
- 將您資料傳送至 Tab 或逗號分隔文字檔,Excel 可以稍後再剖析成儲存格在工作表上。
- 將您的資料傳輸到使用 ADO.NET 的工作表。
- 傳送 XML 資料至 Excel (僅版本 2002年) 提供被格式化和排列在資料列和資料行的資料。
技術
使用自動化來傳輸資料依儲存格
使用自動化,您可以將資料轉換到工作表的一個儲存格一次,如下所示。
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()
傳輸資料的儲存格如果可以是一個可接受的方法並沒有要傳送的資料量。您有彈性,活頁簿中的任何位置放置資料,並可以格式化儲存格有條件地在執行階段。然而,這種方法不建議使用如果您有大量的資料傳送至一個 Excel 活頁簿。您在執行階段取得每一個
Range 物件會產生一個介面要求。因此,轉送資料以這種方式可能會很慢。
此外,Microsoft Windows 95、 Microsoft Windows 98 和 Microsoft Windows 千禧版 (Me) 對是 64 KB 的限制介面要求。如果有 64 KB 或多個介面要求 「 自動化 」 伺服器 (Excel) 可能會停止回應,或者您可能會收到錯誤訊息,指出記憶體不足。 如需詳細資訊,請按一下下列的文件編號,檢視 「 Microsoft 知識庫 」 中的文件:
216400?
(http://support.microsoft.com/kb/216400/
)
跨處理序 COM 自動化可以掛上 Win95/98 的用戶端應用程式
同樣地,傳輸資料的儲存格是可以接受只對小量的資料。如果您必須將大型資料集傳送至 Excel,請考慮使用其他傳輸大量的資料,本文所討論的方法之一。
如需詳細資訊] 和 [如何自動化 Excel 使用 Visual Basic.NET 的範例中,按一下下面的文件編號,檢視 「 Microsoft 知識庫 」 中的發行項在下列文件:
301982?
(http://support.microsoft.com/kb/301982/
)
如何自動化 Microsoft Excel 從 Visual Basic.NET
使用自動化傳送至某個範圍的陣列中的資料工作表上
陣列中的資料可以傳輸到多個儲存格範圍在同一時間,如下所示。
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()
如果藉由使用陣列,而不依儲存格傳輸資料,就可以瞭解與大量資料的龐大的效能增益。請考慮從先前程式碼將資料轉移到 300 的工作表中的儲存格這一行。
oSheet.Range("A2").Resize(100, 3).Value = DataArray
這一行代表兩個介面要求: 一個用於
Range 方法會傳回,將
Range 物件,另一個用於
調整大小 方法會傳回
Range 物件。相較之下,轉送資料依儲存格需要要求的 300 的介面,以
Range 物件。不論何時儘可能,您可以受益減少所做的介面要求的數目及傳送大量資料。
會使用自動化將 ADO 資料錄集傳輸到工作表範圍
物件模型的 Excel 2000 和 Excel 2002 提供
CopyFromRecordset 方法,用於傳輸到範圍的 ADO 資料錄集工作表上。下列程式碼將說明如何自動化 Excel 使用
CopyFromRecordset 方法傳送北風貿易範例資料庫中的 [訂貨主檔] 資料表的內容。
'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()
注意CopyFromRecordset 只能搭配 ADO
資料錄集 物件。您可以使用 ADO.NET 建立
資料集 不能搭配
CopyFromRecordset 方法。請依照下列的章節中的幾個範例會示範如何將資料傳送至 Excel 使用 ADO.NET。
使用自動化,在工作表上建立一個 QueryTable 物件
一個
QueryTable 物件代表透過從外部資料來源傳回的資料所建立的表格。雖然您自動化 Excel 時,您還可以建立
QueryTable 藉由提供連接字串的 OLEDB] 或 [ODBC 資料來源] 和 [SQL 字串。Excel 會產生資料錄集並將資料錄集插入工作表在您指定的位置。使用
QueryTable 物件提供下列勝於
CopyFromRecordset 方法的優勢:
- Excel 會處理資料錄集和它的位置在工作表中的建立。
- 查詢可以儲存與 QueryTable 物件,讓它以取得更新的資料錄集可稍後再更新。
- 當新 QueryTable 新增至您的工作表時,您可以指定資料工作表上的儲存格已有所移位以配合新的資料 (請參閱 RefreshStyle 屬性以取得詳細資料)。
下列程式碼會示範如何自動化 Excel 2000 或 2002年藉由使用北風貿易範例資料庫中的資料建立新的
QueryTable Excel 工作表中。
'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
使用剪貼簿]
您可以使用 [剪貼簿] 來將資料傳送至工作表。若要將資料貼到工作表上的多個儲存格,您可以複製的資料行以 Tab 字元分隔及由換行字元行字元分隔的資料列一個字串。下列程式碼將說明 Visual Basic.NET 如何使用剪貼簿傳送資料至 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()
建立 Excel 可以剖析為資料列和資料行的分隔的文字檔
Excel 可以開啟 Tab 分隔的檔案或以逗號分隔的檔案,並正確地剖析成儲存格的資料。當您想要轉移到工作表的大量資料時使用小如果有任何,小自動化時,您可以使用這項功能。這可能是用戶端與伺服器程式的一個好方法,因為文字檔案可以是產生的伺服器端。然後,您可以開啟文字檔,在用戶端使用 「 自動化很適當。
下列程式碼將說明如何從 ADO.NET 與讀取的資料產生 Tab 分隔的文字檔。
'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()
否自動化已在先前的程式碼中使用。不過,您可以使用最少的自動化,如果您要開啟文字檔案,並將檔案儲存於 [Excel 活頁簿] 格式如下所示。
'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()
使用 ADO.NET 來將資料傳送至工作表
您可以使用 Microsoft Jet OLE DB 提供者將記錄加入現有的 Excel 活頁簿中的資料表。在 Excel 中的 「 表格 」 只是一個儲存格範圍 ; 該範圍可能有已定義的名稱。通常,範圍的第一列包含標頭 (或欄位名稱),然後範圍中所有較新的資料列包含記錄。
下列程式碼中 Book7.xls 在資料表中加入兩個新的記錄。這個資料表在這種情況下是 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()
當如所示,您可以新增記錄具有 ADO.NET 時,維護活頁簿中格式設定。每個新增的資料列的記錄會採用從它前面資料列格式。比方說新增到 B 欄的新欄位會格式化與向右對齊,因為儲存格 B1 是靠右對齊。
請注意當一筆資料錄加入至一個儲存格或工作表中的儲存格,它會覆寫先前那些儲存格所包含的任何資料。亦即工作表中的資料列是不"推 「 加入新記錄時。如果您使用 ADO.NET 打算插入新記錄,在您的工作表上設計版面配置的資料時,請記住這點。
如更多有關如何使用 ADO.NET 的資訊,按一下下面的文件編號,檢視 「 Microsoft 知識庫 」 中 「 文件:
301075?
(http://support.microsoft.com/kb/301075/
)
如何連接到資料庫,並藉由使用 ADO.NET 和 Visual Basic.NET 中執行命令
301216?
(http://support.microsoft.com/kb/301216/
)
如何使用 Visual Basic.NET 填入 DataSet 物件從一個資料庫
301248?
(http://support.microsoft.com/kb/301248/
)
如何使用 Visual Basic.NET 更新 DataSet 物件從一個資料庫
如需有關如何使用 Jet OLE DB 提供者與 Excel 的資料來源的詳細資訊,按一下 [下列面的文件編號,檢視 「 Microsoft 知識庫 」 中的發行項]:
278973?
(http://support.microsoft.com/kb/278973/
)
ExcelADO 示範如何使用 ADO 來讀取和寫入資料在 Excel 活頁簿中
257819?
(http://support.microsoft.com/kb/257819/
)
如何使用 ADO Visual Basic 或 VBA Excel 資料
傳輸 XML 資料 (Excel 2002)
Excel 2002 可以開啟任何語式正確的 XML 檔案。可直接從
開啟 的命令在 [
檔案] 功能表上或以程式設計方式使用
開啟舊檔] 或 [
OpenXML活頁簿 集合的方法開啟 XML 檔案。如果您在 Excel 中建立使用的 XML 檔案,也可以建立樣式表來格式化資料。
如更多有關如何使用 XML 與 Excel 2002 的資訊,按一下下面的文件編號,檢視 「 Microsoft 知識庫 」 中 「 文件:
307021?
(http://support.microsoft.com/kb/307021/
)
如何將 XML 資料傳送至 Microsoft Excel 2002 中,藉由使用 Visual Basic.NET
288215?
(http://support.microsoft.com/kb/288215/
)
Microsoft Excel 2002 和 XML
建立完整的範例 Visual Basic.NET 專案
- 建立新資料夾來存放 Excel 活頁簿範例將為您,建立,並再命名資料夾 C:\Exceldata\。
- 請依照下列步驟執行來建立新的活頁簿,範例中寫入至:
- 在 Excel 中啟動新的活頁簿。
- 新的活頁簿的 Sheet1 請在儲存格 A1 和儲存格 A2 中的 [姓氏] 中輸入 名字。
- 將活頁簿儲存為 C:\Exceldata\Book7.xls。
- 啟動 Visual Studio.NET。在 [檔案] 功能表上按一下 [新增],然後按一下 [專案]。在 Visual Basic 專案 下, 選取 [Windows 應用程式]。依照預設值,會建立 Form1。
- 加入 Excel 物件程式庫的參考。要這麼做,請您執行下列步驟:
- 在 [專案] 功能表上按一下 [加入參考]。
- 在 [COM] 索引標籤上找不到 Microsoft Excel 10.0 物件程式庫,然後按一下 [選取]。
附註如果您已經不這樣,Microsoft 建議您下載並安裝組 [Microsoft Office XP 主要 Interop 件 (PIA)。 如需有關 Office XP PIA,按一下 [下面的文件編號,檢視 「 Microsoft 知識庫 」 中的發行項]: 328912?
(http://support.microsoft.com/kb/328912/
)
Microsoft Office XP 主要 Interop 組件 (PIA) 是可供下載
- 在 [COM] 索引標籤上找到 Microsoft ActiveX 資料物件 2.7 媒體櫃,然後按一下 [選取]。
- 按一下 [[確定] 在 [加入參考] 對話方塊以接受您的選擇。如果接到提示,以產生您所選取的程式庫的包裝函式時,按一下 [是]。
- 將 下拉式方塊 控制項和 按鈕] 控制項加入 Form1。
- 將下列程式碼加入至 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
附註如果您未將 Office 安裝到預設資料夾 (C:\Program Files\Microsoft Office) 變更 sNorthwind 常數在程式碼範例,以符合您的安裝路徑的 Northwind.mdb。
- 將下列程式碼加入至 Form1.vb
Imports Microsoft.Office.Interop
頂端 - 按下 F5 以建置並執行範例。
如需詳細資訊,請造訪下列 Microsoft 開發人員網路 MSDN 網站:
如需詳細資訊,請按一下下列的文件編號,檢視 「 Microsoft 知識庫 」 中的文件:
247412?
(http://support.microsoft.com/kb/247412/
)
從 Visual Basic 傳送資料至 Excel 的方法