zoukankan      html  css  js  c++  java
  • POI 导出excel带小数点的数字格式显示不对解决方法

    最近看到了一个问题就是java导出excel中带小数点的数字显示不对, 比如我想在excel中第一行显示:  3,000.0 但是在excle中导出的格式总是不带小数点 3000(非文本格式),而且也不是以金融格式显示的。这时候我们的解决方法是要为单元格中的数字设置dataformat。代码如下 import java.io.FileOutputStream; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.hssf.usermodel.HSSFDataFormat; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; public class ExcelUtil { public void testWriteExcel() {

     String excelPath = "d:/test.xls";  HSSFWorkbook workbook = null;  try {    // XSSFWorkbook used for .xslx (>= 2007), HSSWorkbook for 03 .xsl    workbook = new HSSFWorkbook();// XSSFWorkbook();//WorkbookFactory.create(inputStream);  } catch (Exception e) {    System.out.println("创建Excel失败: ");    e.printStackTrace();  }  if (workbook != null) {    Sheet sheet = workbook.createSheet("测试数据");    Row row0 = sheet.createRow(0);    for (int i = 0; i < 6; i++) {     double test = 3000.0;     Cell cell = row0.createCell(i, Cell.CELL_TYPE_NUMERIC);    CellStyle cellStyle = workbook.createCellStyle();     HSSFDataFormat df = workbook.createDataFormat();  //此处设置数据格式       cellStyle.setDataFormat(df.getFormat("#,#0.0")); //小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));        cell.setCellStyle(cellStyle);      cell.setCellValue( test );         }    try {      FileOutputStream outputStream = new FileOutputStream(excelPath);      workbook.write(outputStream);      outputStream.flush();      outputStream.close();    } catch (Exception e) {      System.out .println("写入Excel失败: ");      e.printStackTrace();    }  }
    } public static void main(String[] args) {     ExcelUtil eu = new ExcelUtil();     eu.testWriteExcel(); }

    }
    当没设置format的时候,光设置CELL_TYPE_NUMERIC只能让数字在excel中显示为数字类型(非文本类型,而不能保证它小数位和金融格式(每位一个逗号)。

    所以如果要达到要求就必须要设置cell的dataformat如上代码所示。

        CellStyle cellStyle = workbook.createCellStyle();      HSSFDataFormat df = workbook.createDataFormat();  //此处设置数据格式        cellStyle.setDataFormat(df.getFormat("#,#0.0")); //小数点后保留两位,可以写contentStyle.setDataFormat(df.getFormat("#,#0.00"));         cell.setCellStyle(cellStyle);

    这几行代码起了绝对的作用。最后结果如下图说是:

  • 相关阅读:
    单例模式学习(一)
    java线程池学习(一)
    redis面试总结(二)
    redis面试总结(一)
    spark 内存溢出处理
    大数据面试总结(一)
    Spark 知识点总结--调优(一)
    组合数据类型
    一些小细节
    文件归档
  • 原文地址:https://www.cnblogs.com/firstdream/p/8461450.html
Copyright © 2011-2022 走看看