prosource

Apache POI, 새 셀 작성이 행 스타일을 재정의합니다.

probook 2023. 7. 7. 19:06
반응형

Apache POI, 새 셀 작성이 행 스타일을 재정의합니다.

Apache POI를 사용하여 데이터를 .xlsx 파일로 내보내는 중인데 파일에 포함된 행과 셀 중 일부를 스타일로 지정하려고 합니다.

파일이 엑셀 2007+로 읽을 예정이라 XSSF를 사용하고 있습니다.

기본적으로 다음 예제와 같이 전체 행에 대한 검은색 전경색을 인덱스 0으로 설정하는 행 스타일을 설정하려고 합니다.잘 작동하지만 새 셀을 작성할 때마다 새로 작성된 셀은 지정한 행 스타일을 재정의하는 것처럼 스타일이 없습니다.

다음은 제가 무엇을 하고 있는지 보여주기 위한 코드 조각입니다.

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("mySheet");
XSSFRow row = sheet.createRow(0);

XSSFCellStyle myStyle = wb.createCellStyle();           

myStyle.setFillForegroundColor(new XSSFColor(new Color(255, 255, 255)));
myStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);

row.setRowStyle(myStyle); //This works, the whole row is now black

row.createCell(0); // This cell doesn't have a style, the rest of the line stays stylized
row.getCell(0).setCellValue("Test");

*row.createCell(0, Cell.CELL_TYPE_STRING);*도 시도해봤지만 아무것도 바뀌지 않았습니다.

내가 하고 싶은 일을 하는 올바른 방법은 무엇입니까?같은 행에 있는 모든 셀의 스타일이 동일하기 때문에 셀을 만든 후 각 셀의 스타일을 설정할 필요가 없도록 이러한 방식으로 작업을 수행하고자 했습니다.

스타일을 아래와 같이 새로 만든 셀로 설정합니다.

    XSSFCell newCell = row.createCell(0);
    newCell.setCellStyle(myStyle);

스타일을 사용하여 행을 작성하더라도 해당 행의 작성된 셀에는 영향을 주지 않습니다.작성 셀에는 고유한 셀 스타일이 있습니다.row style로 오버라이드되지 않음cell style자동으로.셀에서 행 스타일을 사용하려면 다시 설정해야 합니다.

설정해도row style결국, 그것은 세포에 영향을 미치지 않을 것입니다.

CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
Row r = sheet.createRow(0);
r.setRowStyle(rowStyle);

Cell c1 = r.createCell(0);
c1.setCellValue("Test 1");
c1.setCellStyle(rowStyle);

저는 "setRowStyle"이 원래대로 작동하지 않는다는 것에 동의합니다.

범위(행 또는 다중 행일 수 있음)에 스타일을 적용하기 위해 고유한 함수를 만들었습니다.

public void applyStyleToRange(Sheet sheet, CellStyle style, int rowStart, int colStart, int rowEnd, int colEnd) {
    for (int r = rowStart; r <= rowEnd; r++) {
        for (int c = colStart; c <= colEnd; c++) {
            Row row = sheet.getRow(r);

            if (row != null) {
                Cell cell = row.getCell(c);

                if (cell != null) {
                    cell.setCellStyle(style);
                }
            }
        }
    }
}

언급URL : https://stackoverflow.com/questions/13151462/apache-poi-creating-new-cells-overrides-the-row-style

반응형