Java Apache POI XSSFWorkbook将列数据保存为文本而不是数字。

huangapple go评论68阅读模式
英文:

Java Apache POI XSSFWorkbook saving column data as text instead of numeric

问题

我有一段生成Excel文件的代码,它看起来像这样:

    public static void generateExcel(List<Results> results, String outputPath)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Workbook workbook = new XSSFWorkbook();
        var sheet = workbook.createSheet("Report");

        String[] headerValues = {"Name", "Type", "Price"};


        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headerValues.length; i++) {
            headerRow.createCell(i).setCellValue(headerValues[i]);
        }

        for (var i = 0; i < results.size(); i++) {
            var row = sheet.createRow(i + 1);
            Results summary = results.get(i);
            int colNum = 0;
            for (var header : headerValues) {
                String propertyName = "get" + header;
                Method method = Results.class.getMethod(propertyName);
                Object value = method.invoke(summary);

                if (value != null) {
                    row.createCell(colNum).setCellValue(value.toString());
                } else {
                    row.createCell(colNum).setCellValue("");
                }
                colNum++;
            }

        }

        for (var i = 0; i < headerValues.length; i++) {
            sheet.autoSizeColumn(i);
        }

        String path = Objects.requireNonNullElse(outputPath, "report.xlsx");
        writeToFile(workbook, path, LOG);
    }

现在有一个循环遍历标题值列表并调用先前创建的方法,例如 `getName()`,然后创建一个包含数据的Excel文件。

我现在面临的问题是,Excel文件中的“Price”列被设置为文本,这使得在Excel中进行筛选时很难立即进行,需要进行转换。

我该如何将列设置为数字样式?

我尝试了下面的代码片段,但没有成功。

DataFormat fmt = workbook.createDataFormat();
CellStyle numericStyle = sheet.getWorkbook().createCellStyle();
numericStyle.setDataFormat(fmt.getFormat("0.00"));
sheet.setDefaultColumnStyle(15, numericStyle);


Excel文件仍然被创建,但是值仍然显示在Excel的左侧,必须在进行筛选之前转换为数字。```

<details>
<summary>英文:</summary>

I have this piece of code which generates an excel file which looks something like this:

    public static void generateExcel(List&lt;Results&gt; results, String outputPath)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Workbook workbook = new XSSFWorkbook();
        var sheet = workbook.createSheet(&quot;Report&quot;);

        String[] headerValues = {&quot;Name&quot;, &quot;Type&quot;, &quot;Price&quot;};


        Row headerRow = sheet.createRow(0);
        for (int i = 0; i &lt; headerValues.length; i++) {
            headerRow.createCell(i).setCellValue(headerValues[i]);
        }

        for (var i = 0; i &lt; results.size(); i++) {
            var row = sheet.createRow(i + 1);
            Results summary = results.get(i);
            int colNum = 0;
            for (var header : headerValues) {
                String propertyName = &quot;get&quot; + header;
                Method method = Results.class.getMethod(propertyName);
                Object value = method.invoke(summary);

                if (value != null) {
                    row.createCell(colNum).setCellValue(value.toString());
                } else {
                    row.createCell(colNum).setCellValue(&quot;&quot;);
                }
                colNum++;
            }

        }

        for (var i = 0; i &lt; headerValues.length; i++) {
            sheet.autoSizeColumn(i);
        }

        String path = Objects.requireNonNullElse(outputPath, &quot;report.xlsx&quot;);
        writeToFile(workbook, path, LOG);
    }

There is a loop going through the list of header values and invoking the methods which were created previously e.g  `getName()` and then creating an excel file with the data.

The problem I am facing now is that the price column is set as text in the excel file, which makes it difficult to filter instantly without conversion in excel. 

How do I set the column to numerical style ? 

I&#39;ve tried this snippet of code below to no avail.

DataFormat fmt = workbook.createDataFormat();
CellStyle numericStyle = sheet.getWorkbook().createCellStyle();
numericStyle.setDataFormat(fmt.getFormat("0.00"));
sheet.setDefaultColumnStyle(15, numericStyle);


The excel file is still created, but the values are still seen on the left hand side in the excel and must be converted to numbers before filtering can take place.


</details>


# 答案1
**得分**: 2

单元格格式与单元格类型无关。

请使用`XSSFRow.createCell(int columnIndex, CellType type)`的两个参数版本,并指定适当的类型。

另外,下次在发布之前请先阅读Javadoc。

<details>
<summary>英文:</summary>

Cell format is independent of cell ***TYPE***.

Use the two-argument version of `XSSFRow.createCell(int columnIndex, CellType type)` and specify the appropriate type.

Also, next time please study the Javadoc before posting here.

</details>



huangapple
  • 本文由 发表于 2023年7月18日 05:03:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定