首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 建立 Excel 檔案並匯出資料完整實作教學

     編輯:關於C#

工具與環境

  • Windows 7、Visual Studio 2010、Microsoft Office 2007

專案建立與介面佈局

  1. 新建 Windows Forms Application 專案。
  2. 表單放置:兩個 DataGridView、一個 TextBox、兩個 Button。

準備 Excel 模板並嵌入資源

  1. 建立 Excel 檔案,Sheet1 第一行設定欄位名。
  2. 雙擊專案 Resources.resx,將 Excel 檔案加入資源(名為 Excel)。

核心程式碼步驟

1. 從資源提取 Excel 檔案

string excelPath = AppDomain.CurrentDomain.BaseDirectory + "Excel" + DateTime.Now.Ticks + ".xlsx";
if (System.IO.File.Exists(excelPath)) { /* 已存在處理 */ return; }
try {
  System.IO.FileStream fs = new System.IO.FileStream(excelPath, FileMode.OpenOrCreate);
  fs.SetLength(0);
  fs.Write(Properties.Resources.Excel, 0, Properties.Resources.Excel.Length);
  fs.Close(); fs.Dispose();
  textBox1.Text = "提取 Excel 檔案成功!\r\n";
}
catch (Exception ex) { /* 錯誤處理 */ }

2. 定義 OleDb 連接字串

string strConn = "Provider=Microsoft.Ace.OleDb.12.0;Persist Security Info=False;" +
  "data source=" + @excelPath + ";Extended Properties='Excel 12.0; HDR=yes; IMEX=10'";
// 注意:IMEX=10 而非 1 或 2,避免「可更新查詢」錯誤

3. 顯示所有工作表資訊

DataTable oleDt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
dataGridView1.DataSource = oleDt;

4. 向 Sheet1 插入資料

OleDbCommand cmd = new OleDbCommand("Insert Into [Sheet1$] Values('abc', 'bac', '0', '123456', 'test','測試','aa')", conn);
cmd.ExecuteNonQuery(); // 重複執行插入多筆

注意:存取 Excel 工作表需在名稱後加 $ 符號(如 [Sheet1$])。

5. 查詢並顯示 Sheet1 內容

cmd = new OleDbCommand("Select * From [Sheet1$]", conn);
OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
dataGridView2.DataSource = ds.Tables[0];

6. 列舉 Schema 資訊

DataTable dt = conn.GetSchema();
/* 列印欄位名與資料 */

7. 關閉連線與開啟資料夾

if (conn.State != ConnectionState.Closed) conn.Close();
System.Diagnostics.Process.Start("explorer.exe", AppDomain.CurrentDomain.BaseDirectory);

原始碼下載

C# 建立 Excel 匯出資料完整原始碼

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved