使用poi在excel表中设置样式

时间:2018-05-08 07:04:15

标签: java apache-poi

我想在excel文件中添加样式。我想设置行/列宽和行颜色。我不知道如何添加这个。下面是我编写excel文件的代码。

         workbook = new HSSFWorkbook();
        //create a new work sheet
        sheet = workbook.createSheet("Test Result");
        CellStyle style = sheet.getWorkbook().createCellStyle();
        style.setWrapText(true);

        testresultdata = new LinkedHashMap<String, Object[]>();
        //add test result excel file column header
        //write the header in the first row
        testresultdata.put("1", new Object[]{"Excel First Row", 
        "Excel Second Row", "Excel 3rd Row", "Excel 4th Row"});  //This line i wrote the excel




       Set<String> keyset = testresultdata.keySet();
        int rownum = 0;
        for (String key : keyset) {
            Row row = sheet.createRow(rownum++);
            Object[] objArr = testresultdata.get(key);

            int cellnum = 0;
            for (Object obj : objArr) {
                Cell cell = row.createCell(cellnum++);

                if (obj instanceof Date)
                    cell.setCellValue((Date) obj);
                else if (obj instanceof Boolean)
                    cell.setCellValue((Boolean) obj);
                else if (obj instanceof String)
                    cell.setCellValue((String) obj);
                else if (obj instanceof Double)
                    cell.setCellValue((Double) obj);
            }
        }

当前的excel视图。我想以有条理的方式展示

enter image description here

1 个答案:

答案 0 :(得分:0)

您缺少将样式设置为单元格。

cell.setCellStyle(cellStyle);

        int cellnum = 0;
        for (Object obj : objArr) {
            Cell cell = row.createCell(cellnum++);
            cell.setCellStyle(cellStyle);
            if (obj instanceof Date)
                cell.setCellValue((Date) obj);
            else if (obj instanceof Boolean)
                cell.setCellValue((Boolean) obj);
            else if (obj instanceof String)
                cell.setCellValue((String) obj);
            else if (obj instanceof Double)
                cell.setCellValue((Double) obj);
        }