使用 Java 在 Excel 中应用条件格式

本教程指导如何使用 Java Excel 中应用条件格式。它包含设置开发环境的详细信息、执行任务的步骤列表以及演示如何使用 Java 在 Excel 中使用条件格式的可运行示例代码。您将学习在使用此功能时应用各种条件和格式。

使用 Java 在 Excel 中添加条件格式的步骤

  1. 将 IDE 设置为使用 Aspose.Cells for Java 在 Excel 中添加薄纱
  2. 创建一个新的 workbook 并在所需的工作表中添加条件格式对象
  3. 创建一个单元格区域并将其添加到 FormatConditionCollection 对象
  4. 为格式条件集合对象创建一个新条件
  5. 定义条件的文本格式
  6. 使用此新规则保存工作簿

这些步骤定义了使用 Java* 根据单元格值在 Excel 中添加*条件格式的过程。通过创建工作簿,然后在工作表中添加类 FormatConditionCollection 对象来启动该过程。此 FormatConditionCollection 对象允许添加单元格区域、条件以及条件的格式。

使用 Java 在 Excel 中创建条件格式的代码

import com.aspose.cells.*;
public class Main
{
public static void main(String[] args) throws Exception // Apply Conditional formatting in Excel using Java
{
// Set the licenses
new License().setLicense("License.lic");
// Create a workbook
Workbook spreadsheet = new Workbook();
// Access a sheet
Worksheet sheet = spreadsheet.getWorksheets().get(0);
// Add a conditional formatting
int indexCondFormatting = sheet.getConditionalFormattings().add();
// Access the newly created format condition collection
FormatConditionCollection fcs = sheet.getConditionalFormattings().get(indexCondFormatting);
// Create a cell range
CellArea cellArea = new CellArea();
cellArea.StartRow = 0;
cellArea.EndRow = 9;
cellArea.StartColumn = 0;
cellArea.EndColumn = 0;
// Add area to the format condition collection object
fcs.addArea(cellArea);
// Create a condition
int conditionIndex = fcs.addCondition(FormatConditionType.CELL_VALUE, OperatorType.BETWEEN, "10", "20");
// Access the condition
FormatCondition formatCondition = fcs.get(conditionIndex);
// Set some formatting
formatCondition.getStyle().setBackgroundColor(Color.getRed());
// Save the workbook
spreadsheet.save("output.xlsx");
System.out.println("Done");
}
}

上面的代码使用 Worksheet 类的 ConditionalFormattings 集合同时使用 Java 在 Excel 中应用条件格式。您可以添加各种类型的条件,例如 CELL_VALUE、COLOR_SCALE、DATA_BAR、TOP_10、CONTAINS_TEXT、NOT_CONTAINS_TEXT、TIME_PERIOD 和 BEGINS_WITH 等。运算符类型列表包括 BETWEEN、EQUAL、GREATER_THAN、GREATER_OR_EQUAL、LESS_THAN 和 NOT_BETWEEN 以及其他一些选项。

本文教我们如何使用 Java* 在电子表格中使用*条件格式。如果您想了解在 Excel 中应用过滤器的过程,请参阅 如何使用 Java 在 Excel 中应用过滤器 上的文章。

 简体中文