Working with Core Cell Operations

使用核心单元操作

概述

核心单元 API 支持类型化值、公式存储、通过 CellValueType 进行值类型检查,以及通过 getStringValue() 实现统一的字符串表示。

存储类型化值

import com.aspose.cells_foss.Cell;
import com.aspose.cells_foss.CellValueType;
import com.aspose.cells_foss.Workbook;
import com.aspose.cells_foss.Worksheet;

try (Workbook workbook = new Workbook()) {
    Worksheet sheet = workbook.getWorksheets().get(0);

    Cell a1 = sheet.getCells().get("A1");
    a1.putValue("Revenue");

    Cell b1 = sheet.getCells().get("B1");
    b1.putValue(42500.75);

    Cell c1 = sheet.getCells().get("C1");
    c1.putValue(true);

    Cell d1 = sheet.getCells().get("D1");
    d1.setFormula("=B1*1.2");

    // Type inspection
    System.out.println(a1.getType());  // STRING
    System.out.println(b1.getType());  // NUMBER
    System.out.println(c1.getType());  // BOOLEAN
    System.out.println(d1.getType());  // FORMULA

    workbook.save("typed.xlsx");
}

CellValueType 枚举值

Enum ValueDescription
STRINGputValue(String) 存储的文本值
NUMBERputValue(int)putValue(double) 存储的数值
BOOLEANputValue(boolean) 存储的布尔值
DATE_TIMEputValue(LocalDateTime) 存储的日期/时间值
FORMULAsetFormula(String) 存储的公式字符串
BLANK空单元格 — 未设置任何值

获取字符串值

cell.getStringValue() 返回一个与区域设置无关的字符串,适合显示或下游处理,无论底层值类型如何:

import com.aspose.cells_foss.Cell;
import com.aspose.cells_foss.Workbook;
import com.aspose.cells_foss.Worksheet;

try (Workbook workbook = new Workbook()) {
    Worksheet sheet = workbook.getWorksheets().get(0);
    Cell b1 = sheet.getCells().get("B1");
    b1.putValue(123);
    System.out.println(b1.getStringValue());  // "123" — no decimal point
    workbook.save("string-values.xlsx");
}

公式存储

import com.aspose.cells_foss.Cell;
import com.aspose.cells_foss.CellValueType;
import com.aspose.cells_foss.Workbook;
import com.aspose.cells_foss.Worksheet;

try (Workbook workbook = new Workbook()) {
    Worksheet sheet = workbook.getWorksheets().get(0);
    Cell b1 = sheet.getCells().get("B1");
    b1.putValue(100.0);
    Cell c1 = sheet.getCells().get("C1");
    c1.setFormula("=B1*1.2");
    System.out.println(c1.getType() == CellValueType.FORMULA);  // true
    workbook.save("formulas.xlsx");
}
 中文