C#npoi學習(讀操作)
阿新 • • 發佈:2018-11-07
#####前言
讀取對應的excel為2013版
使用前需要匯入的dll,(百度雲可以獲得)
(還有一點要說的,NPoi只能讀,往Excel檔案中寫入東西,然後儲存會導致檔案損壞,一直沒有找到解決的辦法,顧往excel寫入的方法就沒有寫了)
//需要匯入 using NPOI.HSSF.UserModel; using NPOI.XSSF.UserModel; using NPOI.SS.UserModel; -------------------------------------------------------------------------------------------------------------- ISheet packOutisheet = null; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); XSSFWorkbook xswork = new XSSFWorkbook(fs);//獲取excel文件 sheetContent = xswork.GetSheet(sheetName);//獲取sheet內容 By sheetName sheetContent = xswork.GetSheetAt(sheetIndex);//獲取sheet內容 By sheetIndex //獲取行數 int rowNum = sheetName.LastRowNum; //獲取對應行的列數 int colNum = sheetName.GetRow(rowIndex).LastCellNum; //獲取單元格值 string cellValue = sheetName.GetRow(rowIndex).GetCell(colIndex).ToString();
在讀取時候,還有一些問題
1.列上的字母轉為列數(百度到的,出處忘了 抱歉,沒有連結)
/// <summary> /// 將列字母轉換為數字 /// </summary> /// <param name="columnName"> 列名</param> /// <returns></returns> public static int ToIndex(string columnName) { if (!Regex.IsMatch(columnName.ToUpper(), @"[A-Z]+")) { throw new Exception("invalid parameter"); } int index = 0; char[] chars = columnName.ToUpper().ToCharArray(); for (int i = 0; i < chars.Length; i++) { index += ((int)chars[i] - (int)'A' + 1) * (int)Math.Pow(26, chars.Length - i - 1); } return index - 1; }
2.在讀取的,excel上可能有各種格式,函式等(百度到的,出處忘了 抱歉,沒有連結),無法直接獲取值
public string formatCellValue(ICell cell) { string cellValue = ""; switch (cell.CellType) { case CellType.BLANK: cellValue = string.Empty; break; case CellType.BOOLEAN: cellValue = cell.BooleanCellValue.ToString(); break; case CellType.NUMERIC: if (DateUtil.IsCellDateFormatted(cell))//日期 { cellValue = cell.DateCellValue.ToString(); } else { cellValue = cell.NumericCellValue.ToString(); } break; case CellType.STRING: cellValue = cell.StringCellValue.Trim(); break; case CellType.ERROR: cellValue = cell.ErrorCellValue.ToString(); break; case CellType.FORMULA://公式 try { HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook); e.EvaluateInCell(cell); cellValue = cell.ToString(); } catch { if (DateUtil.IsCellDateFormatted(cell))//日期 { cellValue = cell.DateCellValue.ToString("yyyy-MM-dd HH:mm:ss"); } else { cellValue = cell.NumericCellValue.ToString(); } } break; default: cellValue = cell.ToString(); break; } return cellValue; }