阅读xlsx文件时,Apche POI获取单元格颜色

大家好我正在使用Apche POIApche POI读取一个xlsx文件。 现在我想读取单元格的颜色并在新的xlsx文件上应用相同的颜色。 我该怎么做 我的代码是:

 public void readXLSXFile(String filePath) throws FileNotFoundException, IOException { XSSFRow row; XSSFRow new_row; XSSFSheet sheet; XSSFCell cell; XSSFCell new_cell; XSSFCellStyle cellStyle; XSSFDataFormat dataFormat; XSSFColor color; XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(filePath)); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet new_sheet = (XSSFSheet) workbook.createSheet(); for(int i = 0; i < xssfWorkbook.getNumberOfSheets(); i++ ) { sheet = xssfWorkbook.getSheetAt(i); for(int j =0; j<sheet.getLastRowNum(); j++) { row = (XSSFRow) sheet.getRow(j); new_row = new_sheet.createRow(j); for(int k = 0; k<row.getLastCellNum(); k++) { cell = row.getCell(k); new_cell = new_row.createCell(k); cellStyle = workbook.createCellStyle(); dataFormat = workbook.createDataFormat(); cellStyle.setDataFormat(dataFormat.getFormat(cell.getCellStyle().getDataFormatString())); color = cell.getCellStyle().getFillBackgroundColorColor(); cellStyle.setFillForegroundColor(color); new_cell.setCellStyle(cellStyle); System.out.println(cell.getCellStyle().getFillForegroundColor()+"#"); switch (cell.getCellType()) { case 0: new_cell.setCellValue(cell.getNumericCellValue()); break; case 1: new_cell.setCellValue(cell.getStringCellValue()); break; case 2: new_cell.setCellValue(cell.getNumericCellValue()); break; case 3: new_cell.setCellValue(cell.getStringCellValue()); break; case 4: new_cell.setCellValue(cell.getBooleanCellValue()); break; case 5: new_cell.setCellValue(cell.getErrorCellString()); break; default: new_cell.setCellValue(cell.getStringCellValue()); break; } } } } workbook.write(new FileOutputStream("G:\\lalit.xlsx")); } 

我使用的是Apche POI 3.8。

我发表评论vikiiii的回答。 我以为我会更多地扩展它。 他的答案特定于HSSF(.xls),但HSSF和XSSF类都来自同一个接口,所以代码是相同的,你只需使用XSSF而不是HSSF。 看到你想重复使用我建议使用的颜色:

 XSSFColor bgColor = xssfCell.getCellStyle().getFillBackgroundColorColor(); 

在这里查看Javadoc。 现在要将新单元格设置为该颜色,您可以使用它 。

 secondCell.getCellStyle().setFillBackgroundColor(bgColor); 

我建议查看XSSF和HSSF类所依赖的接口,并了解如何使代码能够处理xls和xlsx文件。 据我所知,唯一的区别是你使用WorkbookFactory设置工作簿的方式 。

您可以使用此代码获取单元格颜色。

 cell.getCellStyle().getFillBackgroundColor(); 

尝试

 HSSFColor.getIndexHash().get(myCell.getCellStyle().getFillBackgroundColor())