buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

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();
    }
}
View Code

 

🍀方法二(推荐)

直接创建一个新的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.]

posted on 2021-12-05 22:42  buguge  阅读(2006)  评论(0)    收藏  举报