【问题标题】:Writing a long value to excel in apache POI在 apache POI 中写入长值以 excel
【发布时间】:2012-07-22 13:01:36
【问题描述】:
当我使用 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
【解决方案1】:
单元格是一般类型而不是数字类型。
你需要这样做 cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
如果您将 365646975447 手动复制粘贴到常规类型的 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
【解决方案2】:
row.createCell(key, CellType.NUMERIC) - 因为不推荐使用 setCellType
【解决方案3】:
在 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);