Number saved as text alert in excel using POI

I get Number stored as text warningfor the created excel file using POI . I'm trying to show a percentage. This question discusses the same thing, but this is for python. Can someone please suggest me how to avoid this in java using POI?

Below are the lines where I get this warning.

workbook= new XSSFWorkbook();
sh1 = wb.createSheet("Data Sheet");
    cell = row.createCell(3);
    cell.setCellValue(37 + "%");

Based on Gagravarr's answer, I did it this way.

XSSFDataFormat df = workbook.createDataFormat();
                    CellStyle cs = wb.createCellStyle();
                    cs.setDataFormat(df.getFormat("%"));
                    cell.setCellValue(0.37);
                    cell.setCellStyle(cs);

But it just displays as .37 without warning, not 37%.

+3
source share
4 answers

You get a warning because, as they say, you save the number as text.

What you probably want to do is:

CellStyle cs = wb.createCellStyle();
cs.setDataFormat(df.getFormat("%"));
cell.setCellValue(0.37);
cell.setCellStyle(cs);

37 excel, . , 37% 0,37, 0,37, 37!

. .xls .xlsx. POI 3.10 final jars .

public class TestPercent {
  public static void main(String[] args) throws Exception {
    System.out.println("Generating...");

    for (Workbook wb : new Workbook[] {new HSSFWorkbook(), new XSSFWorkbook()}) {
        Sheet sheet = wb.createSheet("Data Sheet");
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(3);

        DataFormat df = wb.createDataFormat();
        CellStyle cs = wb.createCellStyle();
        cs.setDataFormat(df.getFormat("%"));
        cell.setCellValue(0.37);
        cell.setCellStyle(cs);

        String output = "/tmp/text.xls";
        if (wb instanceof XSSFWorkbook) { output += "x"; }
        FileOutputStream out = new FileOutputStream(output);
        wb.write(out);
        out.close();
    }

    System.out.println("Done");
  }
}
+4

CellType:

cell.setCellType(Cell.CELL_TYPE_NUMERIC);
+3

, :

df.getFormat("0.00%")
0
    if(NumberUtils.isDigits(text)){
        titleCell.setCellValue(Integer.parseInt(text));
    }else{
        titleCell.setCellValue(text);
    }
0

All Articles