写一个长值以在apache POI中表现出色

问题描述 投票:1回答:2

[当我使用Apache POI将长值写入Excelsheet中的单元格时,它将通过一些数字操作将其写入。示例:

cell = row.createCell(6);
cell.setCellValue(someObt.getLongValue());  
// long value returned is 365646975447
// in excel sheet, it is written as 3.65647E+11.
// but when i click on the cell, i can see 365646975447 as the value.

我希望它在我编写时显示确切的值。我该怎么办?

java excel apache-poi long-integer
2个回答
3
投票

该单元格是常规类型,而不是数字。

您需要执行此cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);

如果手动复制粘贴365646975447到类型为General的Excel单元格中,将显示3.65647E + 11。如果将其更改为数字,则它将正确显示。

尝试一下:

import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;

public class Test
{
    public static void main(String[] args)
    throws Exception
    {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("format sheet");
        CellStyle style;
        DataFormat format = wb.createDataFormat();
        short rowNum = 0;
        short colNum = 0;

        Row row = sheet.createRow(rowNum++);
        Cell cell = row.createCell(colNum);
        cell.setCellValue(365646975447.0);
        style = wb.createCellStyle();
        style.setDataFormat(format.getFormat("0.0"));
        cell.setCellStyle(style);


        FileOutputStream fileOut = new FileOutputStream("workbook.xls");
        wb.write(fileOut);
        fileOut.close();
    }
}    

也请检查:http://poi.apache.org/spreadsheet/quick-guide.html


0
投票

在POI版本4.1中,API如下:

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;

...
XSSFCell cell = row.createCell(key);
cell.setCellType(CellType.NUMERIC);
© www.soinside.com 2019 - 2024. All rights reserved.