【问题标题】:Apache POI cell with multiple lines with different styles具有不同样式的多行的 Apache POI 单元
【发布时间】:2020-12-17 13:54:54
【问题描述】:

我正在尝试实现这样的目标:

如您所见,有些单元格只有 1 行,例如 name 或 112233:

另外,有多行的单元格,每行可能有不同的样式(超链接、背景颜色、纯文本),这可以使用 java 的 apache poi 库吗?找不到任何相关内容。

我正在使用 java 8 和 apache poi 4.1.2。 目前设法创建每行的 excel 以在每列中具有特定类型的 1 个单元格。

try (Workbook workbook = new XSSFWorkbook()) {

        Sheet sheet = workbook.createSheet("sheet");
        Row header = sheet.createRow(0);

        CellStyle hlinkStyle = workbook.createCellStyle();
        CellStyle cellStyle = workbook.createCellStyle();
        CellStyle dateStyle = workbook.createCellStyle();
        CellStyle numberStyle = workbook.createCellStyle();
        CellStyle rowStyle = workbook.createCellStyle();
        rowStyle.setWrapText(true);
        setHeaderAndStyles(workbook, hlinkStyle, dateStyle, numberStyle, cellStyle);
        createHeaders(workbook, sheet, header, null);

        int[] rowNum = {1};
        data.forEach(ele -> {

            Row row = sheet.createRow(rowNum[0]);
            row.setRowStyle(rowStyle);
            int cellIdx = 0;

            // name
            cell = row.createCell(cellIdx++);
            cell.setCellValue(ele.getName());
            cell.setCellStyle(cellStyle);

            // ID
            cell = row.createCell(cellIdx++);
            cell.setCellValue(ele.getId());
            cell.setCellStyle(cellStyle);

            // hyper link
            cell = row.createCell(cellIdx++);
            Hyperlink link = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
            link.setAddress(CONST_URL);
            cell.setCellValue(ele.getHyperLinkText());
            cell.setHyperlink(link);
            cell.setCellStyle(hlinkStyle);
            // need to create more cells here with background color

            // desc
            cell = row.createCell(cellIdx);
            cell.setCellValue(ele.getDesc());
            cell.setCellStyle(cellStyle);
            row.getCell(cellIdx).setCellStyle(rowStyle); // for cells with multiple lines.
            // need to create more cells here with plain text

            rowNum[0]++;
        });
}

谢谢

【问题讨论】:

  • 只是一个小备忘录:如果其中一个答案符合您的需要并且正确回答了您的问题,那么不要忘记将其标记为已接受!

标签: java excel apache-poi export-to-excel


【解决方案1】:

(1) 你要的代码

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
    
// Creating all needed cellStyles
    
XSSFCellStyle noBottomGridLine = workbook.createCellStyle();
noBottomGridLine.setBorderBottom(BorderStyle.THIN);
noBottomGridLine.setBottomBorderColor(IndexedColors.WHITE.index);
XSSFCellStyle noTopGridLine = workbook.createCellStyle();
noTopGridLine.setBorderTop(BorderStyle.THIN);
noTopGridLine.setTopBorderColor(IndexedColors.WHITE.index);
XSSFCellStyle noVerticalGridLine = workbook.createCellStyle();
noVerticalGridLine.setBorderTop(BorderStyle.THIN);
noVerticalGridLine.setTopBorderColor(IndexedColors.WHITE.index);
noVerticalGridLine.setBorderBottom(BorderStyle.THIN);
noVerticalGridLine.setBottomBorderColor(IndexedColors.WHITE.index);
XSSFFont hlinkFont = workbook.createFont();
hlinkFont.setUnderline(Font.U_SINGLE);
hlinkFont.setColor(IndexedColors.BLUE.getIndex());
XSSFCellStyle hlinkStyle = workbook.createCellStyle();
hlinkStyle.setFont(hlinkFont);
XSSFCellStyle coloredStyle = workbook.createCellStyle();
coloredStyle.setFillForegroundColor(IndexedColors.RED.index);
coloredStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
XSSFCellStyle alignedText = workbook.createCellStyle();
alignedText.setVerticalAlignment(VerticalAlignment.TOP);

// Creating merged regions for columns one and two

sheet.addMergedRegion(new CellRangeAddress(0, 5, 0, 0));
sheet.addMergedRegion(new CellRangeAddress(0, 5, 1, 1));

// Removing gridlines from columns three four and five

for (int i = 2 ; i < 5 ; ++i) {
    for (int j = 0 ; j < 6 ; ++j) {
        XSSFRow r = sheet.getRow(j);
        if (r == null) r = sheet.createRow(j);
        if (j == 0) {
            r.createCell(i, CellType.STRING).setCellStyle(noBottomGridLine);
        } else if (j == 5){
            r.createCell(i, CellType.STRING).setCellStyle(noTopGridLine);
        } else {
            r.createCell(i, CellType.STRING).setCellStyle(noVerticalGridLine);
        }
    }
}
    
// Resizing columns
for (int j = 0 ; j < 6 ; ++j) sheet.setColumnWidth(j, 125*50);
    
// First column
    
sheet.getRow(0).createCell(0, CellType.STRING).setCellValue("Name");
sheet.getRow(0).getCell(0).setCellStyle(alignedText);
    
// Second column
sheet.getRow(0).createCell(1, CellType.NUMERIC).setCellValue("112233");
sheet.getRow(0).getCell(1).setCellStyle(alignedText);
    
// Third column
XSSFCell hyperlinkCell = sheet.getRow(0).getCell(2);
hyperlinkCell.setCellValue("hyperlink text");
XSSFHyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
hyperlink.setAddress("https://www.youtube.com/watch?v=mI_y8h22c_o");
hyperlinkCell.setHyperlink(hyperlink);
hyperlinkCell.setCellStyle(hlinkStyle);
XSSFCell backGroundColoredCell = sheet.getRow(2).getCell(2);
backGroundColoredCell.setCellValue("Colored Cell");
backGroundColoredCell.setCellStyle(coloredStyle);
    
// Fourth column
sheet.getRow(0).getCell(3).setCellValue("Team");
sheet.getRow(1).getCell(3).setCellValue("Title");
sheet.getRow(2).getCell(3).setCellValue("New Team");
sheet.getRow(3).getCell(3).setCellValue("New Team");
    
// Fifth column
sheet.getRow(0).getCell(4).setCellValue("Full Team description");
sheet.getRow(1).getCell(4).setCellValue("Full Title Description");
sheet.getRow(2).getCell(4).setCellValue("Origin");
sheet.getRow(3).getCell(4).setCellValue("Code");
            
// Saving Workbook
    
FileOutputStream outputStream = new FileOutputStream("D:\\Desktop\\test-excel.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();

输出:

(2) 关于 XSSFCells 自定义的简短指南

  1. 单元格内的格式化文本
  2. 单元格内的彩色文本
  3. 彩色单元格的背景
  4. 超链接
  5. 将一组单元格合并为一个单元格
  6. 删除单元格的网格线(一个小技巧)

当使用 .xlsx excel 文件时(这意味着使用 XSSF Apache Poi 对象,查看 at this post 以了解 XSSFHSSF Apache Poi 对象之间的差异)您可以使用 XSSFRichTextString 来填充带有一些格式化文本的XSSFCell。使用XSSFRichTextString,您既可以附加与自定义XSSFFont 关联的新文本,也可以使用\n 字符开始新行(如果您在XSSFCellStyleXSSFCell 上调用CellStyle#setWrapTest(true) 为讨论here)。

这是一个例子:

XSSFRichTextString richValue = new XSSFRichTextString();
            
XSSFFont italicBoldFont = workbook.createFont();
italicBoldFont.setBold(true);
italicBoldFont.setItalic(true);
XSSFFont onlyBoldFont = workbook.createFont();
onlyBoldFont.setBold(true);
            
richValue.append("First text", italicBoldFont);
richValue.append("\nSecond text", onlyBoldFont);
            
XSSFCell cell = workbook.getSheetAt(0).createRow(0).createCell(0, CellType.STRING);
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setWrapText(true);
cell.setCellStyle(cellStyle);
cell.setCellValue(richValue);


使用XSSFColor来改变文本颜色可能有点棘手(一些有用的提示herehere),这里是一个例子:

XSSFRichTextString richValue = new XSSFRichTextString();

XSSFFont coloredFont = workbook.createFont();
coloredFont.setColor(IndexedColors.BLUE1.index);
            
richValue.append("Colored text", coloredFont);
            
workbook.getSheetAt(0).createRow(0).createCell(0, CellType.STRING).setCellValue(richValue);


如果你想改变背景颜色,你只能改变一个整个XSSFCell的背景颜色。为此,请使用自定义XSSFCellStyle,如here 所示。这是一个例子:

XSSFCell cell = workbook.getSheetAt(0).createRow(0).createCell(0, CellType.STRING);
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.DARK_RED.index);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cell.setCellStyle(cellStyle);
cell.setCellValue("Some text");


要添加超链接,唯一的方法是创建一个XSSFCell,其中包含该超链接。您必须使用XSSFHyperlink Java 对象和XSSFCell#setHyperlink(Hyperlink hyperlink) 方法。这是一个例子:

XSSFHyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
hyperlink.setAddress("https://www.youtube.com/watch?v=mI_y8h22c_o");
            
XSSFCell cell = workbook.getSheetAt(0).createRow(0).createCell(0, CellType.STRING);
cell.setHyperlink(hyperlink);
cell.setCellValue("Click here to open cute video");

如果你想要一个突出显示的超链接:

XSSFHyperlink hyperlink = workbook.getCreationHelper().createHyperlink(HyperlinkType.URL);
hyperlink.setAddress("https://www.youtube.com/watch?v=mI_y8h22c_o");
            
XSSFCellStyle hlinkStyle = workbook.createCellStyle();
XSSFFont hlinkFont = workbook.createFont();
hlinkFont.setUnderline(Font.U_SINGLE);
hlinkFont.setColor(IndexedColors.BLUE.getIndex());
hlinkStyle.setFont(hlinkFont);
            
XSSFCell cell = workbook.getSheetAt(0).createRow(0).createCell(0, CellType.STRING);
cell.setHyperlink(hyperlink);
cell.setCellValue("Click here to open cute video");
cell.setCellStyle(hlinkStyle);


如果要将一些XSSFCell合并为一个,请使用XSSFSheet#addMergedRegion(CellRangeAddress region)方法,如下所示

sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 2));

其中CellRangeAddress 构造函数需要int firstRow, int lastRow, int firstCol, int lastCol


如果您想从XSSFSheet 中删除所有网格线,请使用XSSFSheet#setDisplayGridlines(boolean show)。如果你想从特定的XSSFCell 中删除网格线,你必须使用这样的技巧(再次利用XSSFCellStyle)(这是使用 Apache Poi 的唯一可能方法):

XSSFCellStyle noUpGridlines = workbook.createCellStyle();
noUpGridlines.setBorderTop(BorderStyle.THIN);
noUpGridlines.setTopBorderColor(IndexedColors.WHITE.index);
            
XSSFCell cell = workbook.getSheetAt(0).createRow(60).createCell(1, CellType.STRING);
cell.setCellStyle(noUpGridlines);
cell.setCellValue("Oh no, where is my top gridline?");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 2016-12-25
    • 1970-01-01
    相关资源
    最近更新 更多