c 使用NPOI快速匯出到excel

2022-03-29 00:37:08 字數 1998 閱讀 9709

接上篇博文《c#快速匯出到excel》:由於此種方法不能匯出成.xlsx格式,為解決此問題,本次分享使用npoi。

參考:1、新增程式包。

在專案名右鍵。

選擇管理nuget程式包,瀏覽處搜尋npoi並安裝。

2、**引用。

using system.io;

using system.data.sqlclient;

using system.diagnostics;

using npoi.hssf.usermodel;

using npoi.ss.usermodel;

using npoi.xssf.usermodel;

3、匯出excel方法:

public void exportdatatoexcel(datatable tablename, string filename)

else if (fileext == ".xls")

else

if (workbook == null)

isheet sheet = string.isnullorempty(filename) ? workbook.createsheet("sheet1") : workbook.createsheet(filename);

//秒鐘

stopwatch timer = new stopwatch();

timer.start();

try//讀取資料

for (int i = 0; i < tablename.rows.count; i++)

//狀態列顯示

rowread++;

percent = (int)(100 * rowread / totalcount);

barstatus.maximum = totalcount;

barstatus.value = rowread;

lblstatus.text = "共有" + totalcount + "條資料,已讀取" + percent.tostring() + "%的資料。";

}//狀態列更改

lblstatus.text = "正在生成excel...";

//轉為位元組陣列

memorystream stream = new memorystream();

workbook.write(stream);

var buf = stream.toarray();

//儲存為excel檔案

using (filestream fs = new filestream(localfilepath, filemode.create, fileaccess.write))

//狀態列更改

lblstatus.text = "生成excel成功,共耗時" + timer.elapsedmilliseconds + "毫秒。";

//關閉秒鐘

timer.reset();

timer.stop();

//成功提示

if (messagebox.show("匯出成功,是否立即開啟?", "提示", messageboxbuttons.yesno, messageboxicon.information) == dialogresult.yes)

//賦初始值

lblstatus.visible = false;

barstatus.visible = false;

}catch (exception ex)

finally}}

4、結果演示:

C 使用NPOI快速匯出到Excel

接上篇博文 c 快速匯出到excel 由於此種方法不能匯出成.xlsx格式,為解決此問題,本次分享使用npoi。參考 1 新增程式包。在專案名右鍵。選擇管理nuget程式包,瀏覽處搜尋npoi並安裝。2 引用。using system.io using system.data.sqlclient u...

c 使用NPOI匯出到excel

1 新增程式包。在專案名右鍵。選擇管理nuget程式包,瀏覽處搜尋npoi並安裝。2 引用。using system.io using system.data.sqlclient using system.diagnostics using npoi.hssf.usermodel using npo...

匯出到Excel中NPOI

1 npoi 感謝tony qu分享出npoi元件的使用方法 3 net呼叫npoi元件匯入匯出excel的操作類 此npoi操作類的優點如下 1 支援web及winform從datatable匯出到excel 2 生成速度很快 3 準確判斷資料型別,不會出現身份證轉數值等問題 4 如果單頁條數大於...