/**DEMO 直接使用工具类中的方法传入参数,模板的生成方法百度一下方法很全,工具在下面的链接里**/
public void exporExcel(HttpServletRequest request, HttpServletResponse response, String startTime,
String endTime) {
String filename = "河南平台开票信息申请表.xls";
String templatePath = request.getRealPath("/" + "freemarkmodel");
File file = null;
InputStream inputStream = null;
OutputStream out = null;
List<BillingInformationBean> selectAllBillingMessage = billingInformationService
.selectAllBillingMessage(startTime, endTime);
Map<String, Object> wr = new HashMap<String, Object>();
wr.put("allBillingMessageList", selectAllBillingMessage);
try {
request.setCharacterEncoding("UTF-8");
file = ExportExcel.createExcel(wr, templatePath, "ptxx.ftl");
inputStream = new FileInputStream(file);
ExportExcel.setXlsHeader(response, filename);
out = response.getOutputStream();
byte[] buffer = new byte[1024]; // 缓冲区
int bytesToRead = -1;
// 通过循环将读入的Excel文件的内容输出到浏览器中
while ((bytesToRead = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, bytesToRead);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
用easyexcel导出
**/
public void download(HttpServletRequest request, HttpServletResponse response, String starttime, String endtime) {
OutputStream out = null;
ExcelWriter writer = null;
String comcode = null;
try {
// 通过查询组装数据
SessionData sessionData = (SessionData) request.getSession().getAttribute(CommonConstants.SESSION_DATA);
comcode = sessionData.getComcode();
if ("ALL".equals(comcode)) {
comcode = null;
}
List<ExportInfo> data = pStatisticsService.getData(starttime, endtime, comcode);
// 拼接导出的文件名
String fileName = new String(("保单数量明细").getBytes("UTF-8"), "ISO-8859-1") + ".xlsx";
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
// 下载到浏览器默认地址
out = response.getOutputStream();
writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
Sheet sheet1 = new Sheet(1, 0, ExportInfo.class);
sheet1.setSheetName("sheet1");
writer.write(data, sheet1);
data.clear();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.flush();
writer.finish();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ExportInfo extends BaseRowModel {
@ExcelProperty(value = "保单号", index = 0)
private String policyno;
@ExcelProperty(value = "投保确认码", index = 1)
private String confirmsequenceno;
public String getPolicyno() {
return policyno;
}
public void setPolicyno(String policyno) {
this.policyno = policyno;
}
public String getConfirmsequenceno() {
return confirmsequenceno;
}
public void setConfirmsequenceno(String confirmsequenceno) {
this.confirmsequenceno = confirmsequenceno;
}
}
工具类地址:https://download.csdn.net/download/u013774699/11709489