I want to write numbers to Excel in scientific notation. In Apache Poi it is possible to set the number format of a cell like this:
Cell cell = ...
CellStyle style = workbook.createCellStyle();
DataFormat format = workbook.createDataFormat();
style.setDataFormat(format.getFormat("#0.00"));
cell.setCellStyle(style);
But when I use a pattern like "#0.00E0"
I get an error from Excel when opening the file and the number format is lost.
Here is a full example:
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();
}
}
}
Thanks!
科学计数法的正确格式为:
format.getFormat("0.00E+00")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.