/// <summary> /// Excel填写模板导出例子 /// </summary> /// <param name="savePath">保存路径</param> /// <returns></returns> public static void ExportToExcelByTemplate() { string savePath = "savepath"; string saveFileName = "template"; string filePath = "Your Template Path"; try { IWorkbook wk; #region 打开Excel表格模板,并初始化到NPOI对象中 if (!File.Exists(filePath)) { return; } string extension = Path.GetExtension(filePath); using FileStream fs = File.OpenRead(filePath); try { wk = new XSSFWorkbook(fs); //07版Eecel } catch (Exception ex) { wk = new HSSFWorkbook(fs); //03版Eecel } fs.Close(); #endregion #region 操作 //写入数据 设置格式 //wk = hssfworkbook; //wk = new XSSFWorkbook(); //获取表,根据SheetId 注意隐藏表 //ISheet sheet = wk.GetSheetAt(2); //ISheet sheet =wk.GetSheetName("SheetName"); //int SheetIndex =wk.GetSheetIndex(SheetObj); //获取行 Cell单元格操作,CreateRow CreateCell或删除原来的内,可以使用Get //IRow Crow = sheet.GetRow(3); //Crow.GetCell(1).SetCellValue(2800); //单元格样式 //ICellStyle style = wk.CreateCellStyle(); //style.BorderBottom = BorderStyle.Thin; //style.BorderLeft = BorderStyle.Thin; //style.BorderRight = BorderStyle.Thin; //style.BorderTop = BorderStyle.Thin; //设置单元格样式 //https://www.cnblogs.com/joean/p/4661056.html #endregion #region 保存文件 string path = savePath; bool exist = Directory.Exists(path); savePath = $"{path}{saveFileName}.xlsx"; if (exist == false) { Directory.CreateDirectory(path); } wk.SaveFile(savePath); wk = null; #endregion } catch { } }