我的方案是从" Status"获取文字。列和基于文本比较,我想突出显示那个特定的单元格。下面是我的代码 -
private static void colorSheet(String xlsxFileAddress)
{
try
{
FileInputStream file = new FileInputStream(new File(xlsxFileAddress));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFFormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
XSSFSheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type after eveluating formulae
//If it is formula cell, it will be evaluated otherwise no change will happen
switch (evaluator.evaluateInCell(cell).getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "tt");
break;
case Cell.CELL_TYPE_STRING:
{
System.out.print(cell.getStringCellValue() + "tt");
ConditionalFormattingRule rule2 = sheetCF.createConditionalFormattingRule(ComparisonOperator.EQUAL,"Extra Rows in new table");
org.apache.poi.ss.usermodel.PatternFormatting fill2 = rule2.createPatternFormatting();
fill2.setFillBackgroundColor(IndexedColors.BLUE.index);
fill2.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
CellRangeAddress[] regions = {
CellRangeAddress.valueOf("A2:A7")
};
sheetCF.addConditionalFormatting(regions, rule2);
break;
}
}
}
System.out.println("");
}
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
我希望无论哪个单元格都有文字&#34;新表中的额外行&#34;应该以蓝色突出显示,但我的代码不起作用。请提示需要。
答案 0 :(得分:0)
好的,问题是您正在读取文件并更改其在进程内存中的内容,但您永远不会将更改写回文件。
尝试更换:
file.close();
使用:
file.close();
FileOutputStream writeFile = new FileOutputStream(new File(xlsxFileAddress));
workbook.write(writeFile);
writeFile.close();
答案 1 :(得分:0)
可能是因为
ConditionalFormattingRule“等于”仅在以ComparisonOperator.EQUAL, "\"" + "Extra Rows in new table" + "\""
而不是(ComparisonOperator.EQUAL,"Extra Rows in new table");
在file.close()
之后添加此内容以写回文件。
FileOutputStream writeFile = new FileOutputStream(new
File(xlsxFileAddress));
workbook.write(writeFile);
writeFile.close();