網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
C#使用NPOI實(shí)現(xiàn)Excel和DataTable的互轉(zhuǎn)_C#教程
作者:林深時(shí)見(jiàn)祿 ? 更新時(shí)間: 2022-04-25 編程語(yǔ)言什么是NPOI?
NPOI是指構(gòu)建在POI 3.x版本之上的一個(gè)程序,NPOI可以在沒(méi)有安裝Office的情況下對(duì)Word或Excel文檔進(jìn)行讀寫(xiě)操作。
NPOI是一個(gè)開(kāi)源的C#讀寫(xiě)Excel、WORD等微軟OLE2組件文檔的項(xiàng)目。
使用NuGet安裝NPOI
NuGet直接搜索NPOI,目前版本是v2.4.1,將其安裝至項(xiàng)目即可。
安裝完成后,項(xiàng)目會(huì)自動(dòng)為我們添加這4個(gè)引用
同時(shí)還需要在程序中引入NPOI.SS.UserModel;NPOI.XSSF.UserModel;NPOI.HSSF.UserModel;三個(gè)命名空間
廢話(huà)不多說(shuō),直接上代碼
DataTable導(dǎo)出Excel
////// Datable導(dǎo)出成Excel /// /// /// 導(dǎo)出路徑(包括文件名與擴(kuò)展名) public static void TableToExcel(DataTable dt, string file) ? ? ? ? { ? ? ? ? ? ? IWorkbook workbook; ? ? ? ? ? ? string fileExt = Path.GetExtension(file).ToLower(); ? ? ? ? ? ? if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; } ? ? ? ? ? ? if (workbook == null) { return; } ? ? ? ? ? ? ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName); ? ? ? ? ? ? ? //表頭 ? ? ? ? ? ? ? IRow row = sheet.CreateRow(0); ? ? ? ? ? ? for (int i = 0; i < dt.Columns.Count; i++) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ICell cell = row.CreateCell(i); ? ? ? ? ? ? ? ? cell.SetCellValue(dt.Columns[i].ColumnName); ? ? ? ? ? ? } ? ? ? ? ? ? ? //數(shù)據(jù) ? ? ? ? ? ? ? for (int i = 0; i < dt.Rows.Count; i++) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? IRow row1 = sheet.CreateRow(i + 1); ? ? ? ? ? ? ? ? for (int j = 0; j < dt.Columns.Count; j++) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ICell cell = row1.CreateCell(j); ? ? ? ? ? ? ? ? ? ? cell.SetCellValue(dt.Rows[i][j].ToString()); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? ? //轉(zhuǎn)為字節(jié)數(shù)組 ? ? ? ? ? ? ? MemoryStream stream = new MemoryStream(); ? ? ? ? ? ? workbook.Write(stream); ? ? ? ? ? ? var buf = stream.ToArray(); ? ? ? ? ? ? ? //保存為Excel文件 ? ? ? ? ? ? ? using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write)) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? fs.Write(buf, 0, buf.Length); ? ? ? ? ? ? ? ? fs.Flush(); ? ? ? ? ? ? } ? ? ? ? }
Excel導(dǎo)入DataTable
////// Excel導(dǎo)入成Datable /// /// 導(dǎo)入路徑(包含文件名與擴(kuò)展名) ///public static DataTable ExcelToTable(string file) ? ? ? ? { ? ? ? ? ? ? DataTable dt = new DataTable(); ? ? ? ? ? ? IWorkbook workbook; ? ? ? ? ? ? string fileExt = Path.GetExtension(file).ToLower(); ? ? ? ? ? ? using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? //XSSFWorkbook 適用XLSX格式,HSSFWorkbook 適用XLS格式 ? ? ? ? ? ? ? ? if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; } ? ? ? ? ? ? ? ? if (workbook == null) { return null; } ? ? ? ? ? ? ? ? ISheet sheet = workbook.GetSheetAt(0); ? ? ? ? ? ? ? ? ? //表頭 ? ? ? ? ? ? ? ? ? IRow header = sheet.GetRow(sheet.FirstRowNum); ? ? ? ? ? ? ? ? List columns = new List (); ? ? ? ? ? ? ? ? for (int i = 0; i < header.LastCellNum; i++) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? object obj = GetValueType(header.GetCell(i)); ? ? ? ? ? ? ? ? ? ? if (obj == null || obj.ToString() == string.Empty) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? dt.Columns.Add(new DataColumn("Columns" + i.ToString())); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? else ? ? ? ? ? ? ? ? ? ? ? ? dt.Columns.Add(new DataColumn(obj.ToString())); ? ? ? ? ? ? ? ? ? ? columns.Add(i); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? //數(shù)據(jù) ? ? ? ? ? ? ? ? ? for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? DataRow dr = dt.NewRow(); ? ? ? ? ? ? ? ? ? ? bool hasValue = false; ? ? ? ? ? ? ? ? ? ? foreach (int j in columns) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? dr[j] = GetValueType(sheet.GetRow(i).GetCell(j)); ? ? ? ? ? ? ? ? ? ? ? ? if (dr[j] != null && dr[j].ToString() != string.Empty) ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? hasValue = true; ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? if (hasValue) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? dt.Rows.Add(dr); ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? return dt; ? ? ? ? } ? ? ? ? ? /// ? ? ? ? /// 獲取單元格類(lèi)型 ? ? ? ? /// ? ? ? ? /// ? ? ? ? ///? ? ? ? private static object GetValueType(ICell cell) ? ? ? ? { ? ? ? ? ? ? if (cell == null) ? ? ? ? ? ? ? ? return null; ? ? ? ? ? ? switch (cell.CellType) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? case CellType.Blank: //BLANK: ? ? ? ? ? ? ? ? ? ? ? return null; ? ? ? ? ? ? ? ? case CellType.Boolean: //BOOLEAN: ? ? ? ? ? ? ? ? ? ? ? return cell.BooleanCellValue; ? ? ? ? ? ? ? ? case CellType.Numeric: //NUMERIC: ? ? ? ? ? ? ? ? ? ? ? return cell.NumericCellValue; ? ? ? ? ? ? ? ? case CellType.String: //STRING: ? ? ? ? ? ? ? ? ? ? ? return cell.StringCellValue; ? ? ? ? ? ? ? ? case CellType.Error: //ERROR: ? ? ? ? ? ? ? ? ? ? ? return cell.ErrorCellValue; ? ? ? ? ? ? ? ? case CellType.Formula: //FORMULA: ? ? ? ? ? ? ? ? ? default: ? ? ? ? ? ? ? ? ? ? return "=" + cell.CellFormula; ? ? ? ? ? ? } }
原文鏈接:https://blog.csdn.net/xiaolu1014/article/details/98454110
相關(guān)推薦
- 2022-03-19 基于React?Hooks的小型狀態(tài)管理詳解_React
- 2022-06-30 C++?select模型簡(jiǎn)單聊天室的實(shí)現(xiàn)示例_C 語(yǔ)言
- 2022-10-26 Golang?Mutex?原理詳細(xì)解析_Golang
- 2022-10-30 C++中線(xiàn)程池ThreadPool源碼解析_C 語(yǔ)言
- 2022-07-16 不同存圖方式下的DFS和BFS實(shí)現(xiàn)
- 2022-08-25 C/C++內(nèi)存管理基礎(chǔ)與面試_C 語(yǔ)言
- 2022-10-12 pyinstaller將python程序打包為可執(zhí)行文件_python
- 2021-12-02 Spring?Boot?分層打包?Docker?鏡像實(shí)踐及分析(推薦)_docker
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支