apache poi apply one style to different workbooks

前端 未结 1 1175
梦谈多话
梦谈多话 2021-02-13 17:13

I\'m trying to apply one cell style to defferent woekbooks. It works well, when I apply it to first workbook, but when I\'m trying to do this with second and next workbooks - no

相关标签:
1条回答
  • 2021-02-13 17:50

    You can't do that, CellStyle objects are specific to one workbook. They're quite deep objects, and much of the style is held in the workbook, so you can't just re-use. You even get a helpful exception which explains this to you!

    What you need to do instead is to use the cloneStyleFrom(CellStyle) method, to copy the details of the style over. Something like:

    Workbook wb = WorkbookFactory.create(new File("existing.xls"));
    CellStyle origStyle = wb.getCellStyleAt(1); // Or from a cell
    
    Workbook newWB = new XSSFWorkbook();
    Sheet sheet = newWB.createSheet();
    Row r1 = sheet.createRow(0);
    Cell c1 = r1.createCell(0);
    
    CellStyle newStyle = newWB.createCellStyle();
    newStyle.cloneStyleFrom(origStyle);
    c1.setCellStyle(newStyle);
    
    newWB.write(new FileOutpuStream("new.xlsx"));
    
    0 讨论(0)
提交回复
热议问题