private static void ReadExcel(string path) { IWorkbook workbook; ISheet _sheet; string fileExt = Path.GetExtension(path); using (var file = new FileStream(path, FileMode.Open, FileAccess.Read)) { if (fileExt == ".xls") { workbook = new HSSFWorkbook(file); } else { workbook = new XSSFWorkbook(file); } } _sheet = workbook.GetSheetAt(0); _sheet.GetRow(0).GetCell(0).SetCellValue("1"); using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write)) { workbook.Write(fs); } }
四个npoi的dll都需要导入,编辑完后如果想覆盖源文件,需要把FileMode设置成Create否则Excel会打不开。