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

    POI 导出excel带小数点的数字格式显示不对解决方法

    2016年01月19日 18:27:04 忽略的爱 

    最近看到了一个问题就是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);

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

  • 相关阅读:
    Oracle 导入导出 dmp 文件
    zTree树
    下拉复选框
    jQuery Pagination分页插件
    下载java生成PDF
    Activiti 流程实例、任务、执行对象及相关的表
    Activiti 删除key值相同的所有不同版本的流程定义
    Activiti 查询最新版本的流程定义
    Activiti 查看流程图
    Activiti 删除流程定义
  • 原文地址:https://www.cnblogs.com/grj001/p/12225582.html
Copyright © 2011-2022 走看看