本文示範使用 Borland C#Builder (Enterprise 版) 搭配 ODBC 連線 Microsoft Access 2000,讀取資料顯示於 ListBox,再透過 COM Interop 匯出至 Excel 2000 的完整流程與程式碼。
mydb.mdb,資料表「聯絡人」欄位:聯絡人ID、名字、姓氏、地址、城市、省份。Component → Installed .NET Components 勾選 ODBC 元件,工具箱將出現 OdbcConnection、OdbcCommand 等。OdbcConnection (ConnectionString: DSN=mydb;Uid=admin;Pwd=)。OdbcCommand (Connection: odbcConnection1, CommandText: select * from 聯絡人)。private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
odbcConnection1.Open();
OdbcDataReader reader = odbcCommand1.ExecuteReader();
try
{
while (reader.Read())
{
// 依欄位索引讀取,實務建議用 GetString(欄位名) 或 GetOrdinal
listBox1.Items.Add($"{reader.GetString(0)},{reader.GetString(1)} {reader.GetString(2)}");
}
}
finally
{
reader.Close();
odbcConnection1.Close();
}
}
TlbImp.exe (SDK 工具) 與 Excel9.olb (Office 2000 類別庫)。TlbImp Excel9.olb 產生 Excel.dll、Office.dll、VBIDE.dll。private void button2_Click(object sender, EventArgs e)
{
int i = 2; // 資料起始列
Excel.Application xlApp = new Excel.Application();
xlApp.Workbooks.Add(true);
xlApp.Visible = true;
// 標題列
xlApp.Cells[1, 4] = "聯絡人";
xlApp.Cells[2, 1] = "聯絡人ID";
xlApp.Cells[2, 2] = "名字";
xlApp.Cells[2, 3] = "姓氏";
xlApp.Cells[2, 4] = "地址";
xlApp.Cells[2, 5] = "城市";
xlApp.Cells[2, 6] = "省份";
listBox1.Items.Clear();
odbcConnection1.Open();
OdbcDataReader reader = odbcCommand1.ExecuteReader();
try
{
while (reader.Read())
{
i++;
xlApp.Cells[i, 1] = reader.GetString(0);
xlApp.Cells[i, 2] = reader.GetString(1);
xlApp.Cells[i, 3] = reader.GetString(2);
xlApp.Cells[i, 4] = reader.GetString(3);
xlApp.Cells[i, 5] = reader.GetString(4);
xlApp.Cells[i, 6] = reader.GetString(5);
}
}
finally
{
reader.Close();
odbcConnection1.Close();
}
// 實務上應釋放 COM 物件:Marshal.ReleaseComObject(xlApp) 等
}
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.Odbc;
using System.IO;
using System.Reflection;
// Excel Interop 命名空間視產生的 DLL 而定,通常為 Excel, Office, VBIDE
namespace DBApp
{
public class WinForm : System.Windows.Forms.Form
{
private OdbcConnection odbcConnection1;
private OdbcCommand odbcCommand1;
private ListBox listBox1;
private Button button1, button2;
private Container components = null;
public WinForm() { InitializeComponent(); }
protected override void Dispose(bool disposing) { /* ... */ }
#region Windows Form Designer generated code
private void InitializeComponent()
{
// 設計工具產生的元件初始化碼 (連線字串、CommandText、控制項屬性、事件繫結)
}
#endregion
[STAThread]
static void Main() { Application.Run(new WinForm()); }
private void button1_Click(object sender, EventArgs e) { /* 查詢邏輯 */ }
private void button2_Click(object sender, EventArgs e) { /* 匯出 Excel 邏輯 */ }
}
}
按 F9 執行,點擊「查詢」ListBox 顯示資料,點擊「匯出」啟動 Excel 並寫入資料。若 Excel 未關閉,後續執行會建立新視窗,建議在 finally 區塊加入 xlApp.Quit() 並釋放 COM 物件。
OleDbConnection 搭配 Microsoft.ACE.OLEDB.12.0 Provider,或改用 Entity Framework Core + SQLite/LocalDB。