欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用NPOI庫(kù)讀寫(xiě)Excel文件

 更新時(shí)間:2022年02月21日 16:26:44   作者:t_z_l  
這篇文章主要為大家詳細(xì)介紹了C#使用NPOI庫(kù)讀寫(xiě)Excel文件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了C#使用NPOI庫(kù)讀寫(xiě)Excel文件的具體代碼,供大家參考,具體內(nèi)容如下

第一步添加程引用: 右鍵項(xiàng)目工程 — 管理 NuGet程序包 — 搜索 NOPI — 安裝

對(duì)文件Excel進(jìn)行操作

讀取excel文件

private IWorkbook wk; ?
private FileStream fs;?
private void OpenExcel(string path)
? ? ? ? {
? ? ? ? ? ? StringBuilder sbr = new StringBuilder();
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? using (fs = File.OpenRead(path)) ? //打開(kāi)myxls.xls文件
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? wk = new XSSFWorkbook(fs); ? //把xls文件中的數(shù)據(jù)寫(xiě)入wk中
?
? ? ? ? ? ? ? ? ? ? for (int i = 0; i < wk.NumberOfSheets; i++) ?//NumberOfSheets是myxls.xls中總共的表數(shù)
? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ISheet sheet = wk.GetSheetAt(i); ? //讀取當(dāng)前表數(shù)據(jù)
?
? ? ? ? ? ? ? ? ? ? ? ? for (int j = 0; j <= sheet.LastRowNum; j++) ?//LastRowNum 是當(dāng)前表的總行數(shù)
? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? IRow row = sheet.GetRow(j); ?//讀取當(dāng)前行數(shù)據(jù)
? ? ? ? ? ? ? ? ? ? ? ? ? ? if (row != null)
? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sbr.Append("-------------------------------------\r\n"); //讀取行與行之間的提示界限
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? for (int k = 0; k <= row.LastCellNum; k++) ?//LastCellNum 是當(dāng)前行的總列數(shù)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ICell cell = row.GetCell(k); ?//當(dāng)前表格
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (cell != null)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sbr.Append(cell.ToString()); ? //獲取表格中的數(shù)據(jù)并轉(zhuǎn)換為字符串類(lèi)型
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? MessageBox.Show("文件被其他應(yīng)用打開(kāi),請(qǐng)關(guān)閉對(duì)該文件的引用?。?!");
? ? ? ? ? ? }
? ? ? ? }

修改 寫(xiě)入

private void SetCellValue(ISheet sheet,int row,int column,String value)
?{
? ? ? ? ? ? ICell tmpCell = sheet.GetRow(row).GetCell(column);
? ? ? ? ? ? tmpCell.SetCellValue(value);
}

保存

private void SaveExcel(String path)
{
? ? ? ? ? ? //把編輯過(guò)后的工作薄重新保存為excel文件
? ? ? ? ? ? FileStream fs2 = File.Create(path);
? ? ? ? ? ? wk.Write(fs2);
? ? ? ? ? ? fs2.Close();
? ? ? ? ? ? MessageBox.Show("文件修改成功!??!");
?}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論