iReport 导出html 和excl文件
fileName 报表的魔板
jsonStr 报表对应的json格式
jsonStr 导出路径
type 类型 1 html 2 excl
@SuppressWarnings("deprecation")
public static String getMode(String fileName, String jsonStr, String extPath,int type) {
byte[] bytes = null;
JasperReport report = null;
String str = "";
JasperDesign design;
try {
design = JRXmlLoader.load(fileName);
HashMap<String, Object> paramsMap = new HashMap<String, Object>();
// 第二种配置数据源的方式 InputStream
InputStream is = null;
try {
is = new ByteArrayInputStream(jsonStr.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
paramsMap.put("JSON_INPUT_STREAM", is);
// 配置其他参数
paramsMap.put(JsonQueryExecuterFactory.JSON_LOCALE, Locale.ENGLISH);
paramsMap.put(JRParameter.REPORT_LOCALE, Locale.US);
// 加载模板
report = JasperCompileManager.compileReport(design);
// 填充数据
JasperPrint print = JasperFillManager.fillReport(report, paramsMap);
// // 预览显示
// JasperViewer.viewReport(print);
ByteArrayOutputStream oStream = new ByteArrayOutputStream();
switch(type){
case 1:
// 生成html 测试成功
JRHtmlExporter html = new JRHtmlExporter();
html.setParameter(JRHtmlExporterParameter.JASPER_PRINT, print);
// html.setParameter(JRHtmlExporterParameter.OUTPUT_FILE_NAME, extName);// 生成文件
html.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
Boolean.FALSE);
html.setParameter(JRExporterParameter.CHARACTER_ENCODING, "utf-8");
html.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, oStream);
html.exportReport();
break;
case 2:
// 生成excel
// File file = new File("D:/test1.excel");
File file = new File(extPath);
OutputStream out = null;
try {
out = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JRXlsExporter xls = new JRXlsExporter();
xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, print);
xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, out);
xls.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.FALSE);
xls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
Boolean.FALSE);
xls.exportReport();
break;
}
bytes = oStream.toByteArray();
try {
str = new String(bytes, "Utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 转化为String字符串,输出字符串的内容
} catch (JRException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}