POI写入excel但是显示不出来问题的快速解决方法
今天在使用POI将float类型数据写EXCEL入时候会出现写入的数值与实际数值不符的问题;例如我将数据4444.4443写入EXCEL中(已将数据精度设置为:df.getFormat("#,##0.0"))出现问题图及正常图详见下图。此问题在从数据库中读出记录写入EXCEL时出现,直接往EXCEL文件中写入数据时完全正常;在数据库读出记录后打印出来也是完全正常的,请高手赐教,部分代码如下:
从数据库读出记录后写入:
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import jcmh.com.bean.JdbcUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class TestPoi {
public static void main(String[] args) throws Exception{
try{
FileOutputStream out = new FileOutputStream("dateFormat.xls");
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
Connection conn = JdbcUtils.getConnection();
Statement stmt = conn.createStatement();
HSSFSheet sheet = hssfworkbook.createSheet("new sheet");
HSSFCellStyle cs = hssfworkbook.createCellStyle();
HSSFDataFormat df = hssfworkbook.createDataFormat();
cs.setDataFormat(df.getFormat("#,##0.0"));
ResultSet rs = stmt.executeQuery("select price from test.test"); //就一条记录为"4444.4443"
while(rs.next()){
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
System.out.println(rs.getFloat(1));
cell.setCellValue(rs.getFloat(1));
cell.setCellStyle(cs);
}
hssfworkbook.write(out);
out.close();
}catch(Exception e){}
}
}
直接写入时代码如下:
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class TestPoi {
public static void main(String[] args) throws Exception{
try{
FileOutputStream out = new FileOutputStream("dateFormat.xls");
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfworkbook.createSheet("new sheet");
HSSFCellStyle cs = hssfworkbook.createCellStyle();
HSSFDataFormat df =hssfworkbook.createDataFormat();
cs.setDataFormat(df.getFormat("#,##0.0"));
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(4444.4443);
cell.setCellStyle(cs);
hssfworkbook.write(out);
out.close();
}catch(Exception e){}
}
需要保留本文链接地址:http://www.excelxx.com/xuexixinde/11655.html