- 引用
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
- 获取方法
public static List<(string, byte[])> GetCNamesWithColor(string path, int sheetIndex = 0, int fieldRowIndex = 0){//列名List < (string, byte[])> result = new List<(string, byte[])();//获取文件流using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){IWorkbook workbook;//获取excel的文件类型ExcelType type = GetExcelFileType(path).Value;//通过不同的文件类型创建不同的读取接口(xls使用HSSFWorkbook类实现,xlsx使用XSSFWorkbook类实现)switch (type){case ExcelType.xlsx:workbook = new XSSFWorkbook(stream);break;default:workbook = new HSSFWorkbook(stream);break;}//ISheet sheet = null;//获取工作表,默认获取第一张if (workbook.NumberOfSheets > sheetIndex && workbook.NumberOfSheets > 0){//获取excel表格sheet = workbook.GetSheetAt(sheetIndex);}else{System.Windows.Forms.MessageBox.Show("索引超出界限或该文件表格为空!");}//是否已经获取工作表,如果没有则直接返回if (sheet == null){return null;}#region//获取表头,文本类型//获取列名(默认获取第一行)if (fieldRowIndex > sheet.LastRowNum)//判断行标是否超界{return null;}IRow headRow = sheet.GetRow(fieldRowIndex);//列数int cellcount = headRow.LastCellNum;for (int i = 0; i < cellcount; i++){//获取行中的i个元素ICell cell = headRow.GetCell(i);byte[] rgb = null;switch (type){case ExcelType.xlsx:rgb = ((NPOI.XSSF.UserModel.XSSFColor)cell.CellStyle.FillForegroundColorColor).RGB;break;default:rgb = ((NPOI.HSSF.Util.HSSFColor)cell.CellStyle.FillForegroundColorColor).RGB;break;}var info = cell.ToString();//将列名添加至数组result.Add((info, rgb));}#endregion}return result;}
- 关键代码:
由于xlsx和xls格式对应的Excel文档要用不同的对象去转换获取对应的Color对象然后访问对应的rgb属性
byte[] rgb = null;switch (type){case ExcelType.xlsx:rgb = ((NPOI.XSSF.UserModel.XSSFColor)cell.CellStyle.FillForegroundColorColor).RGB;break;default:rgb = ((NPOI.HSSF.Util.HSSFColor)cell.CellStyle.FillForegroundColorColor).RGB;break;}