POI设置Excel行或单元格的背景色
POI:set background color for a row or a cell.
use setFillForegroundColor and setFillPattern at the same.
Note that not setFillBackgroundColor.
XSSFCellStyle newstyle = wb.createCellStyle();
newstyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
newstyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
POI:set the last sheet selected, use setActiveSheet method.
XSSFWorkbook wb = new XSSFWorkbook(inputStream); ... wb.setActiveSheet(newExcelCreat.getNumberOfSheets() - 1);
利用POI清空excel文件
就是说,删掉指定excel文件里的所有sheet页。
🍀方法一(不推荐)
这种方式,虽然删掉了所有sheet,但是excel文件大小没变。可能是因为删除工作表并不会立即释放文件所占用的空间。在Excel中,删除工作表只是将其标记为删除,但实际上并没有从文件中删除相关数据。所以,欠妥!

public static void removeAllSheets(File excelFile) { XSSFWorkbook workbook= null; try { workbook = new XSSFWorkbook(new FileInputStream(excelFile)); int numberOfSheets = workbook.getNumberOfSheets(); for (int i = numberOfSheets - 1; i >= 0; i--) { workbook.removeSheetAt(i); } workbook.createSheet("Sheet1"); FileOutputStream fileOut = new FileOutputStream(excelFile); workbook.write(fileOut); fileOut.flush(); fileOut.close(); } catch (IOException e) { e.printStackTrace(); } }
🍀方法二(推荐)
直接创建一个新的Workbook对象,然后写入到文件里。相当于重新创建了一个同名的文件,里面只有一个默认的Sheet1,文件大小是4k。
public static void truncateFile(File excelFile) { try { XSSFWorkbook workbook = new XSSFWorkbook(); workbook.createSheet("Sheet1"); FileOutputStream fileOut = new FileOutputStream(excelFile); workbook.write(fileOut); fileOut.flush(); fileOut.close(); workbook.close(); } catch (IOException e) { e.printStackTrace(); } }
[The End.]
当看到一些不好的代码时,会发现我还算优秀;当看到优秀的代码时,也才意识到持续学习的重要!--buguge
本文来自博客园,转载请注明原文链接:https://www.cnblogs.com/buguge/articles/15647508.html