简体   繁体   English

如何在 Apache POI 中制作带有“逗号样式”单元格的 excel 工作表?

[英]How to make excel sheet with "comma style" cell in Apache POI?

My task is to format excel file to "comma style".我的任务是将 excel 文件格式化为“逗号样式”。 For example I have value 0 or 0.00 in my cell, and I press "," button in excel例如,我的单元格中的值为 0 或 0.00,然后我按 excel 中的“,”按钮

在此处输入图像描述

as a result my value becomes "-".结果我的价值变成了“-”。

在此处输入图像描述

if I have value "Hello"如果我有价值“你好”

在此处输入图像描述

after pressing this button - value moves little bit right:按下此按钮后 - 值向右移动一点点:

在此处输入图像描述

My task is to emulate pressing this button in Apache poi, how can I do it?我的任务是模拟在 Apache poi 中按下这个按钮,我该怎么做?

I have no idea how to do it, All I could find is formatting below: but it doesn't work:我不知道该怎么做,我只能找到以下格式:但它不起作用:

public class Test {
public static void main(String s[]) {
    try{
        FileOutputStream out = new FileOutputStream
                ("dateFormat.xls");
        HSSFWorkbook hssfworkbook = new HSSFWorkbook();
        HSSFSheet sheet = hssfworkbook.createSheet
                ("new sheet");
        HSSFCellStyle cs = hssfworkbook.createCellStyle();
        HSSFDataFormat df = hssfworkbook.
                createDataFormat();
        cs.setDataFormat(df.getFormat("#,##0.0"));
        HSSFRow row = sheet.createRow((short)0);
        HSSFCell cell = row.createCell((short)0);
        cell.setCellValue(11111.0);
        cell.setCellStyle(cs);

        HSSFCell cell2 = row.createCell((short)1);
        cell2.setCellValue(0);
        cell2.setCellStyle(cs);

        HSSFCell cell3 = row.createCell((short)2);
        cell3.setCellValue("hello");
        cell3.setCellStyle(cs);

        hssfworkbook.write(out);
        out.close();
    }catch(Exception e){}
}
}

Also I have separate task - if value is 1.0 it should become 1, if you could help me with this formatting would be great!我还有单独的任务——如果值是 1.0,它应该变成 1,如果你能帮我处理这个格式就太好了!

I'm not sure about that code, I had a similar task but parsed the numbers myself... Here's the code, not sure if it's gonna help you though:我不确定该代码,我有一个类似的任务但我自己解析了数字......这是代码,但不确定它是否会帮助你:


private String getNumericValue(final String raw) {
    final double value = Double.parseDouble(raw);
    final String strValue = String.valueOf(new BigDecimal(value).setScale(1, RoundingMode.CEILING).doubleValue()).replace('.', ',');
    if (strValue.endsWith(",0"))
        return strValue.substring(0, (strValue.length() - 2));
    return strValue;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM