jasper生成excel,单元格数据格式问题:
现象:比如某个数据为1.34400,但是在excel中则显示成1.344,导致后面的0被忽略掉
第一张图就是未解决之前的效果,第二张图则是解决之后的效果
解决方法:
JRXlsExporterParameter.IS_DETECT_CELL_TYPE 属性设置为: Boolean.FALSE
下面附上jasper生成excel文件的源代码:
/**
*
* @param datas 数据集
* @param jrxmlOfPath jrxml文件路径
* @param params 相关参数
* @param fileName 文件名
*/
public static void excelWithJrxml(List<?> datas, String jrxmlOfPath, Map<String, Object> params, String fileName) {
byte[] content = null;
ByteArrayOutputStream baos = null;
try {
InputStream inputStream = ReportUtil.class.getClassLoader().getResourceAsStream(jrxmlPath);
JasperDesign design = JRXmlLoader.load(inputStream);
JasperReport report = JasperCompileManager.compileReport(design);
JRDataSource datasource = new JRBeanCollectionDataSource(datas);
JasperPrint jasperPrint = JasperFillManager.fillReport(report, params, datasource);
JRXlsExporter jRXlsExporter = new JRXlsExporter();
jRXlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
jRXlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
jRXlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
jRXlsExporter.setParameter(JRXlsExporterParameter.SHEET_NAMES,
new String[] { fileName });
baos = new ByteArrayOutputStream();
jRXlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
jRXlsExporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
jRXlsExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.FALSE);
jRXlsExporter.exportReport();
content = baos.toByteArray();
testWriteLocalFile(content,"xls");
} catch (Exception e) {
logger.error("generate excel fail exception {}", e);
} finally {
if (baos != null) {
IOUtil.close(baos);
}
}
}
/**
* 本地写文件
* @param bytes
* @param fileType
*/
public static void testWriteLocalFile(byte[] bytes,String fileType){
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file;
String filePath = "/Users/yq/Documents/work/";
try {
File dir = new File(filePath);
if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
dir.mkdirs();
}
file = new File(filePath + "a." + fileType);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}