Core Cell Operations

如何在 Java 中使用核心单元操作

概述

Cell 类是存储和读取电子表格数据的核心单元。本指南涵盖类型化值存储、类型检查、公式存储以及字符串值访问。

存储类型化值

Cell.putValue() 接受六种 Java 类型:String、int、double、boolean、LocalDateTime 和 Object。每次调用都会存储该值并确定由 cell.getType() 返回的 CellValueType。使用与数据匹配的类型化重载——调用 putValue(int) 可存储一个整数,该整数在往返过程中不会出现小数点:

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

try (Workbook workbook = new Workbook()) {
    WorksheetCollection sheets = workbook.getWorksheets();
    Worksheet sheet = sheets.get(0);
    Cell a1 = sheet.getCells().get("A1");
    a1.putValue("Label");        // String
    Cell b1 = sheet.getCells().get("B1");
    b1.putValue(42);             // int
    Cell c1 = sheet.getCells().get("C1");
    c1.putValue(3.14);           // double
    Cell d1 = sheet.getCells().get("D1");
    d1.putValue(true);           // boolean
    workbook.save("typed.xlsx");
}

检查值类型

调用 cell.getType() 可获取任意已存储值的 CellValueType 枚举值。使用 cell.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()) {
    WorksheetCollection sheets = workbook.getWorksheets();
    Worksheet sheet = sheets.get(0);
    Cell b1 = sheet.getCells().get("B1");
    b1.putValue(123);
    CellValueType type = b1.getType();
    System.out.println(type);           // NUMBER
    System.out.println(b1.getStringValue());  // "123"
    workbook.save("inspect.xlsx");
}

存储公式

使用标准 Excel 公式字符串调用 cell.setFormula()。单元格类型会更改为 CellValueType.FORMULA,且公式会保存在 XLSX 文件中;打开文件时 Excel 会重新计算结果。

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

try (Workbook workbook = new Workbook()) {
    WorksheetCollection sheets = workbook.getWorksheets();
    Worksheet sheet = sheets.get(0);
    Cell b1 = sheet.getCells().get("B1");
    b1.putValue(100.0);
    Cell c1 = sheet.getCells().get("C1");
    c1.setFormula("=B1*1.2");
    workbook.save("formulas.xlsx");
}

另请参阅

 中文