網站首頁 編程語言 正文
本文實例為大家分享了C#用NPOI導出導入Excel幫助類的具體代碼,供大家參考,具體內容如下
1、準備工作
在管理NuGet程序包中搜索 NPOI,安裝 NPOI 到要項目中。
2、幫助類
////// DataTable寫入Excel /// /// /// ///public bool GridToExcelByNPOI(DataTable dt, string strExcelFileName) { ? ? try ? ? { ? ? ? ? HSSFWorkbook workbook = new HSSFWorkbook(); ? ? ? ? ISheet sheet = workbook.CreateSheet("Sheet1"); ? ? ? ? ICellStyle HeadercellStyle = workbook.CreateCellStyle(); ? ? ? ? HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; ? ? ? ? //字體 ? ? ? ? NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont(); ? ? ? ? headerfont.Boldweight = (short)FontBoldWeight.Bold; ? ? ? ? HeadercellStyle.SetFont(headerfont); ? ? ? ? //用column name 作為列名 ? ? ? ? int icolIndex = 0; ? ? ? ? IRow headerRow = sheet.CreateRow(0); ? ? ? ? foreach (DataColumn item in dt.Columns) ? ? ? ? { ? ? ? ? ? ? ICell cell = headerRow.CreateCell(icolIndex); ? ? ? ? ? ? cell.SetCellValue(item.ColumnName); ? ? ? ? ? ? cell.CellStyle = HeadercellStyle; ? ? ? ? ? ? icolIndex++; ? ? ? ? } ? ? ? ? ICellStyle cellStyle = workbook.CreateCellStyle(); ? ? ? ? //為避免日期格式被Excel自動替換,所以設定 format 為 『@』 表示一率當成text來看 ? ? ? ? cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@"); ? ? ? ? cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; ? ? ? ? NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont(); ? ? ? ? cellfont.Boldweight = (short)FontBoldWeight.Normal; ? ? ? ? cellStyle.SetFont(cellfont); ? ? ? ? //建立內容行 ? ? ? ? int iRowIndex = 1; ? ? ? ? int iCellIndex = 0; ? ? ? ? foreach (DataRow Rowitem in dt.Rows) ? ? ? ? { ? ? ? ? ? ? IRow DataRow = sheet.CreateRow(iRowIndex); ? ? ? ? ? ? foreach (DataColumn Colitem in dt.Columns) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ICell cell = DataRow.CreateCell(iCellIndex); ? ? ? ? ? ? ? ? cell.SetCellValue(Rowitem[Colitem].ToString()); ? ? ? ? ? ? ? ? cell.CellStyle = cellStyle; ? ? ? ? ? ? ? ? iCellIndex++; ? ? ? ? ? ? } ? ? ? ? ? ? iCellIndex = 0; ? ? ? ? ? ? iRowIndex++; ? ? ? ? } ? ? ? ? //自適應列寬度 ? ? ? ? for (int i = 0; i < icolIndex; i++) ? ? ? ? { ? ? ? ? ? ? sheet.AutoSizeColumn(i); ? ? ? ? } ? ? ? ? //寫Excel ? ? ? ? FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate); ? ? ? ? workbook.Write(file); ? ? ? ? file.Flush(); ? ? ? ? file.Close(); ? ? ? ? return true; ? ? } ? ? catch (Exception ex) ? ? { ? ? ? ? return false; ? ? } } /// /// 將excel中的數據導入到DataTable中 /// /// fileName /// excel工作薄sheet的名稱 /// 第一行是否是DataTable的列名 ///返回的DataTable public DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn) { ? ? ISheet sheet = null; ? ? DataTable data = new DataTable(); ? ? IWorkbook workbook = null; ? ? FileStream fs = null; ? ? int startRow = 0; ? ? try ? ? { ? ? ? ? fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); ? ? ? ? if (fileName.IndexOf(".xlsx") > 0) // 2007版本 ? ? ? ? ? ? workbook = new XSSFWorkbook(fs); ? ? ? ? else if (fileName.IndexOf(".xls") > 0) // 2003版本 ? ? ? ? ? ? workbook = new HSSFWorkbook(fs); ? ? ? ? if (sheetName != null) ? ? ? ? { ? ? ? ? ? ? sheet = workbook.GetSheet(sheetName); ? ? ? ? ? ? if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet ? ? ? ? ? ? { ? ? ? ? ? ? ? ? sheet = workbook.GetSheetAt(0); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? else ? ? ? ? { ? ? ? ? ? ? sheet = workbook.GetSheetAt(0); ? ? ? ? } ? ? ? ? if (sheet != null) ? ? ? ? { ? ? ? ? ? ? IRow firstRow = sheet.GetRow(0); ? ? ? ? ? ? int cellCount = firstRow.LastCellNum; //一行最后一個cell的編號 即總的列數 ? ? ? ? ? ? if (isFirstRowColumn) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? for (int i = firstRow.FirstCellNum; i < cellCount; ++i) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ICell cell = firstRow.GetCell(i); ? ? ? ? ? ? ? ? ? ? if (cell != null) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? string cellValue = cell.StringCellValue; ? ? ? ? ? ? ? ? ? ? ? ? if (cellValue != null) ? ? ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? ? ? DataColumn column = new DataColumn(cellValue); ? ? ? ? ? ? ? ? ? ? ? ? ? ? data.Columns.Add(column); ? ? ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? startRow = sheet.FirstRowNum + 1; ? ? ? ? ? ? } ? ? ? ? ? ? else ? ? ? ? ? ? { ? ? ? ? ? ? ? ? startRow = sheet.FirstRowNum; ? ? ? ? ? ? } ? ? ? ? ? ? //最后一列的標號 ? ? ? ? ? ? int rowCount = sheet.LastRowNum; ? ? ? ? ? ? for (int i = startRow; i <= rowCount; ++i) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? IRow row = sheet.GetRow(i); ? ? ? ? ? ? ? ? if (row == null) continue; //沒有數據的行默認是null ? ? ? ? ? ? ? ? DataRow dataRow = data.NewRow(); ? ? ? ? ? ? ? ? for (int j = row.FirstCellNum; j < cellCount; ++j) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null ? ? ? ? ? ? ? ? ? ? ? ? dataRow[j] = row.GetCell(j).ToString(); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? data.Rows.Add(dataRow); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? return data; ? ? } ? ? catch (Exception ex) ? ? { ? ? ? ? Console.WriteLine("Exception: " + ex.Message); ? ? ? ? return null; ? ? } }
3、使用
(1)DataTable寫入Excel
var Sql = "select id,name from test"; var dt = DB.DB.ExecuteDataTable(Sql); //保存文件 string saveName = "temp_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"; string DownloadExcelDic = "DownloadExcel"; string webDic = AppDomain.CurrentDomain.BaseDirectory + DownloadExcelDic; if (!Directory.Exists(webDic))//判斷目錄是否存在 { ? ? Directory.CreateDirectory(webDic);//不存在則創建新目錄 } string path = webDic + @"\" + saveName; //目錄+文件名+后綴名 bool isBuild = GridToExcelByNPOI(dt, path);
(2)導入Excel返回DataTable
//1、先上傳文件,將文件保存到服務器上 //2、導入Excel string fileDic = "";//文件路徑 var dt = ExcelToDataTable(fileDic, "sheet1", true);
原文鏈接:https://blog.csdn.net/lbx_15887055073/article/details/82194414
相關推薦
- 2022-06-08 優化使用Feign進行Rpc調用,支持對象傳參自動轉換
- 2023-01-09 Spark處理trick總結分析_相關技巧
- 2022-05-01 WinForm中Application.Idle方法詳解_C#教程
- 2022-06-22 Android使用http實現注冊登錄功能_Android
- 2022-10-24 centos編譯安裝mariadb的詳細過程_mariadb
- 2022-05-03 shell腳本批量創建用戶的方法小結_linux shell
- 2022-03-24 Android使用Span打造豐富多彩的文本詳解_Android
- 2022-07-28 聊聊docker跨主機之間容器通信問題_docker
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支