popcoder
popcoder

Reputation: 3070

Writing a long value to excel in apache POI

When i write a long value to a cell in Excelsheet using Apache POI, it writes it with some numerical manipulation. Example:

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.

I want it to display the exact value as i write. How can i do this?

Upvotes: 2

Views: 7663

Answers (3)

Kseniia
Kseniia

Reputation: 23

row.createCell(key, CellType.NUMERIC) - since setCellType is deprecated

Upvotes: 2

yglodt
yglodt

Reputation: 14551

In POI version 4.1 the API is as follows:

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

...
XSSFCell cell = row.createCell(key);
cell.setCellType(CellType.NUMERIC);

Upvotes: 0

Spiff
Spiff

Reputation: 4104

The cell is of type general and not numeric.

You need to do this cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);

If you copy paste 365646975447 by hand in an Excel Cell that is of type General it will be displayed 3.65647E+11. If you change it to numeric then it displays correctly.

Try this:

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();
    }
}    

Also check: http://poi.apache.org/spreadsheet/quick-guide.html

Upvotes: 4

Related Questions