Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用ApachePOI中ss模型提供的单元格样式_Java_Excel_Apache Poi_Excel 2007_Excel 2003 - Fatal编程技术网

Java 使用ApachePOI中ss模型提供的单元格样式

Java 使用ApachePOI中ss模型提供的单元格样式,java,excel,apache-poi,excel-2007,excel-2003,Java,Excel,Apache Poi,Excel 2007,Excel 2003,我试图使我为XSSF工作簿编写的代码同时兼容xls和xlsx。下面给出一段代码作为示例 Workbook workbook = WorkbookFactory.create(new File("F:\\JavaEE\\test.xls")); Sheet sheet = workbook.getSheetAt(0); short cellBorderColour = IndexedColors.GREY_80_PERCENT.getIndex(); Font font = workbook.

我试图使我为XSSF工作簿编写的代码同时兼容xls和xlsx。下面给出一段代码作为示例

Workbook workbook = WorkbookFactory.create(new File("F:\\JavaEE\\test.xls"));
Sheet sheet = workbook.getSheetAt(0);

short cellBorderColour = IndexedColors.GREY_80_PERCENT.getIndex();

Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
font.setColor(IndexedColors.BLUE_GREY.index);

CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
cellStyle.setFont(font);

cellStyle.setBorderLeft(CellStyle.BORDER_HAIR);
cellStyle.setLeftBorderColor(cellBorderColour);
cellStyle.setBorderTop(CellStyle.BORDER_HAIR);
cellStyle.setTopBorderColor(cellBorderColour);
cellStyle.setBorderRight(CellStyle.BORDER_HAIR);
cellStyle.setRightBorderColor(cellBorderColour);
cellStyle.setBorderBottom(CellStyle.BORDER_MEDIUM);
cellStyle.setBottomBorderColor(cellBorderColour);

Row row = sheet.createRow(1);
Cell cell = row.createCell(1);

sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 4));
borderRowCells(1, 4, row, cell, cellStyle);
cell.setCellValue("Value");

FileOutputStream fos = new FileOutputStream("F:\\JavaEE\\new_test.xls");
workbook.write(fos);

//Take care of exception handling and closing of the stream.
上述代码用于跨越合并单元格边界的实用程序方法

private void borderRowCells(int from, int to, Row row, Cell cell, CellStyle cellStyle) {
    for (int i = from; i <= to; ++i) {
        cell = row.createCell(i);
        cell.setCellStyle(cellStyle);
    }
}
甚至是更好/不同的东西


PS:我正在使用ApachePOI3.10.1。

如果你只是使用它,有什么不起作用?为了使用
XSSFColor
,它需要
XSSFCellStyle
XSSFCellStyle-cellStyle=(XSSFCellStyle)工作簿。createCellStyle()不适用于xls格式-
java.lang.ClassCastException:org.apache.poi.hssf.usermodel.HSSFCellStyle不能强制转换为org.apache.poi.xssf.usermodel.XSSFCellStyle
这两种文件格式对颜色的处理非常不同,因此很遗憾,不可能为这两种颜色提供通用代码。您需要测试单元格样式的类型,然后以特定于格式的方式创建/分配颜色。。。然后,它就像创建了两个不同的方法来处理xls和xlsx格式。是的,有一些情况下,文件格式太不同,无法用一个常见的情况来概括,您已经找到了其中一个。。。
XSSFColor commonColor = new XSSFColor(new java.awt.Color(240, 240, 240));