我想以科学记数法将数字写入 Excel。在 Apache Poi 中,可以像这样设置单元格的数字格式:
Cell cell = ...
CellStyle style = workbook.createCellStyle();
DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("#0.00"));
cell.setCellStyle(style);
但是当我使用像 "#0.00E0"
这样的模式时,我在打开文件时收到 Excel 错误,并且数字格式丢失。
这是一个完整的示例:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Main {
public static void main(String[] args) {
try (Workbook wb = new XSSFWorkbook();
FileOutputStream fos = new FileOutputStream("out.xlsx")) {
Sheet sheet = wb.createSheet();
Cell cell = sheet.createRow(0).createCell(0);
CellStyle style = wb.createCellStyle();
DataFormat format = wb.createDataFormat();
style.setDataFormat(format.getFormat("#0.00E0"));
cell.setCellStyle(style);
cell.setCellValue(Math.random());
wb.write(fos);
} catch (Exception e) {
e.printStackTrace();
}
}
}
谢谢!
最佳答案
科学计数法的正确格式是:
format.getFormat("0.00E+00")
关于java - Apache POI : How to write numbers in scientific format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50254885/