java - Apache POI : How to write numbers in scientific format

标签 java apache-poi

我想以科学记数法将数字写入 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/

相关文章:

java - 关于 SXSSFWorkbook 关于 FlushedRows、Written to Disk 和 rowAccessWindowSize 的问题

java - 使用 poi 打印十进制值和电话号码

java - 具有依赖项的 Maven .jar 文件无法在除生成该文件的设备之外的任何其他设备上运行

java - 通过隐式导航重定向到 servlet?

Java ArrayList 接口(interface)类型

java - FileOutputStream 正在将文件大小减小到 0

java - 如何使用 apache poi 更改特定 word 文档的颜色?

java - 我最近将我的项目转换为 Maven。但出现错误Resource read error : Could not load com/sun/xml/txw2/Content. class

java - 将值保存到数据库

java - 使用 org.apache.poi.xssf.usermodel.XSSFWorkbook 在 java 中创建 excel 时移动 excel 中的列