首页 文章

Apache POI:如何以科学格式编写数字

提问于
浏览
0

我想用科学记数法将数字写入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();
        }
    }
}

谢谢!

1 回答

  • 3

    科学记数法的正确格式是:

    format.getFormat("0.00E+00")
    

相关问题