C 建立Excel檔案並將資料匯出到Excel檔案

2021-09-02 02:56:13 字數 2351 閱讀 6220

工具原料:

windows 7,visual studio 2010, microsoft office 2007

建立解決方案

選單》新建》專案》windows窗體應用程式:

新增兩個datagridview,乙個textbox,兩個按鈕 ,如下圖:

新增excel資源:

c#建立excel檔案,這裡實際上是從資源中提取乙個事先建立好的excel檔案,檔案提取成功後,使用oledb方法連線excel,向excel檔案中寫入資料。

先在資料夾中新建乙個excel檔案,在sheet1表的第一行設定列名:

雙擊「resources.resx」檔案開啟資源檔案檢視:

新增現有檔案,選擇剛剛建立的excel檔案

從資源中提取excel檔案

if (system.io.file.exists(excelpath))

trycatch (system.exception ex)

定義連線字串

//定義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'";

oledbconnection conn = new oledbconnection();

conn.connectionstring = strconn;

注意:連線字串中imex的值使用的是10,如果是1或2,在執行insert into語句時就會報「操作必須使用乙個可更新的查詢」的錯誤。

在datagridview1中顯示excel檔案中的所有表的資訊

datatable oledt = conn.getoledbschematable(oledbschemaguid.tables, null);

datagridview1.datasource = oledt;

datagridview1.show();

向"sheet1"表中插入幾條資料,訪問excel的表的時候需要在表名後新增"$"符號,insert語句可以不指定列名

oledbcommand cmd = null;

trycatch (system.exception ex)

在datagridview2中顯示表"sheet1"的內容,訪問excel的表的時候需要在表名後新增"$"符號

cmd = new oledbcommand("select * from [sheet1$]", conn);

oledbdataadapter adp = new oledbdataadapter(cmd);

dataset ds = new dataset();

adp.fill(ds);

datagridview2.datasource = ds.tables[0];

遍歷schema的內容

datatable dt = conn.getschema();

for (int i = 0; i < dt.columns.count; i++)

}for (int j = 0; j < dt.rows.count; j++)

else

if (i + 1 < dt.columns.count)

}textbox1.text += ("\r\n");

}

關閉excel資料連線
if (conn.state != connectionstate.closed)

catch (system.exception ex)

}

開啟檔案目錄

讀取excel檔案並將其中資料轉換成指令碼資料結構

最近寫 測試了在unity中讀取excel配置檔案,將配置中的資料結構自動寫成指令碼中的資料結構。要寫的excel檔案如下 角色資訊表 boss資訊表 讀取excel檔案並寫成指令碼的 using unityengine using system.collections using excel us...

C 導excel及 格式控制

格式控制 xst.get range excel.cells 1,1 excel.cells 1,1 horizontalalignment excel.xlhalign.xlhaligncenter 對齊方式 xst.get range excel.cells 1,1 excel.cells 1,...

java poi技術將Excel檔案內容匯入資料庫

最近在做檔案 poi解析excel 檔案步驟 1.獲取excel檔案的資料流 2.建立hssfworkbook 物件 3.然後就是獲取sheet物件,4.最後就是解析sheet物件內的相關資料,public list readexceltitle inputstream is catch ioexc...