NPOI對excel檔案的匯入匯出

2022-03-21 08:12:23 字數 1681 閱讀 9081

現理解:將乙個excel檔案(工作簿-iworkbook)看做是乙個你要操作的物件,每個工作簿包含多個工作表(isheet)物件,每個工作表中又包含多個行物件(irow),每行又包含多個單元格(icell)物件.  單元格裡儲存相應資料

下面幫助更直觀的展示:iworkbook --> isheet --> irow --> icell

一:從資料庫中將符合條件的資料匯出到乙個新的excel中

思路:0.ado獲取匯入內容

1.建立乙個iworkbook物件.我們最終將把這個設定好的iworkbook物件寫入到乙個檔案流中,即大功告成.

2.建立這個iworkbook的isheet物件.

3.建立這個isheet的irow物件.

4.建立irow的icell物件,並設定資料庫裡相應的值

注:sqlhelper將不再附上

//

將資料庫中的表的資料匯出到execel表中

string sqlstr = "

select * from t_scripts";

using (sqldatareader dr =sqlhelper.executereader(sqlstr))

int n = 1

;

while

(dr.read())

}n++;

}//將iworkbook物件寫入到檔案流中

using (filestream fs = file.create("

d:/tscript.xls"))

messagebox.show(

"out success!");}}

view code

二:將excel檔案中的內容錄入到資料庫中

思路:0.開啟乙個excel檔案流.

1.將這個流附加到新建的乙個iworkbook物件上.此時已經拿到這個檔案的物件

2.獲取這個工作簿的isheet物件

3.獲取isheet的irow物件

4.進行ado操作,將每行的資料以此新增到資料庫表中

1

string sqlstr = "

insert into t_customers ( cc_customername, cc_cellphone, cc_landline, cc_carnum, cc_bracketnum, cc_buydate) values (@name,@phone,@sphone,@carnum,@bk,@date)";

2//將要錄入資料庫的xls通過流的方式傳給乙個iworkbook物件

3using (filestream infs = file.open(@"

客戶資料new.xls

", filemode.open))4;

20for (int j = 0; j < datarow.lastcellnum; j++)

2127

else

2831

}32 sqlhelper.executenonquery(sqlstr, spt);//

插入到資料庫表中的相應列33}

34}35 messagebox.show("

access!

");

view code

不同版本的nopi程式設計貌似有些不同

npoi匯入匯出excel

1.匯入 將datatable資料匯入到excel中 要匯入的資料 datatable的列名是否要匯入 要匯入的excel的sheet的名稱 匯入資料行數 包含列名那一行 public int datatabletoexcel datatable data,string sheetname,bool...

Npoi匯入匯出Excel操作

datatable匯出excel private static void gridtoexcelbynpoi datatable dt,string strexcelfilename icellstyle cellstyle workbook.createcellstyle 為避免日期格式被exce...

NPOI實現 Excel匯入匯出

實現物件集合寫入到excel和excel資料讀出到物件集合的功能 自定義列屬性 public class columnattribute attribute public columnattribute string columnname 時間格式 public class datetimeform...