Cara Bekerja dengan Operasi Sel Inti di Java
Overview
Pengelolaan Cell kelas adalah unit inti untuk menyimpan dan membaca data spreadsheet. Panduan ini mencakup penyimpanan nilai yang diketik, inspeksi tipe, penyimpanan rumus, dan akses ke string value.
Menyimpan Nilai yang Ditulis
Cell.putValue() menerima enam jenis Java: String, int, double, boolean, LocalDateTime, dan Object.Setiap panggilan menyimpan nilai dan menentukan CellValueType dikembalikan oleh: cell.getType().Gunakan overload yang tertulis sesuai dengan data panggilan . putValue(int) menyimpan bilangan bulat yang melakukan perjalanan bolak-balik tanpa mendapatkan titik desimal:
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");
}Jenis nilai yang diperiksa
Call cell.getType() untuk mendapatkan CellValueType nilai enum untuk setiap nilai yang disimpan. Gunakan cell.getStringValue() untuk mendapatkan representasi string independen dari lokasi, terlepas dari tipe yang mendasarinya:
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");
}Rumus Penyimpanan
Call cell.setFormula() dengan string rumus Excel standar. Jenis sel berubah menjadi CellValueType.FORMULA dan rumus disimpan dalam file XLSX; Excel menghitung kembali hasilnya saat file dibuka:
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");
}