您的位置:首页 > 其它

使用JXL 模板导出数据

2016-07-15 15:40 344 查看
action层

@RequestMapping("/person/exportPersonToExcel")
@ResponseBody
public ActionResult exportPersonToExcel() {
ActionResult result = new ActionResult(true);
try {
personInfoService.exportPersonInfo(this.getServletResponse());
} catch (IOException e) {
result.setMessage(e.getMessage());
result.setSuccess(false);
LogUtils.logException(e);
}
return result;
}


2.service 层, 这里我们要使用 .xls 的模板进行操作的

找到当前web路径下的模板 WebContextUtils.getWebContextRootPath()

public static String getWebContextRootPath(){
ServletContext servletContext = HttpRequestUtils.getServletContext();
if (servletContext != null){
return servletContext.getRealPath(FILE_SEPARATOR);
}

return EMPTY_STRING;
}


下的文件 xls的路径

得到输出流 OutputStream os = getOutputStreamForExcelExport(httpServletResponse);

private OutputStream getOutputStreamForExcelExport(HttpServletResponse response) {
OutputStream os = null;
try {
os = response.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.reset();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
String dateString = sdf.format(new Date());
response.setHeader("Content-disposition", "attachment; filename=\"person" + dateString + ".xls\"");
response.setContentType("application/msexcel");
return os;
}


向输出流中写入数据

private void exportPersonToSheet(WritableSheet sheet) {
int row = 0;
int col = 0;
try {
List<PersonInfo> personList =personDao.getPersonListByStatus();
if (!CollectionUtils.isEmpty(personList)) {
for (PersonInfo p : personList) {
col = 0;
row++;// 第一行为标题信息,模板中有
sheet.addCell(new Label(col++, row, p.getPersonCode()));// 编号
sheet.addCell(new Label(col++, row, p.getName()));// 姓名
sheet.addCell(new Label(col++, row, p.getDepartmentName()));
}
}

} catch (Exception e) {
LogUtils.logException(e);
}
}


3. 整个流程呢

public void exportPersonInfo(HttpServletResponse httpServletResponse) throws IOException {
if (httpServletResponse != null) {
OutputStream os = getOutputStreamForExcelExport(httpServletResponse);
WritableWorkbook wbook = null;
InputStream is = null;
try {
is = new FileInputStream(WebContextUtils.getWebContextRootPath()
+ ConstParamOnecard.PERSON_EXCEL_PATH_EXPORT);
wbook = Workbook.createWorkbook(os, Workbook.getWorkbook(is));
WritableSheet sheet = wbook.getSheet(0);
exportPersonToSheet(sheet);
this.recordPersonModuleLog(I18NMsgUtils.getMessage("log.onecard.person.operate.exportPerson"));
} catch (IOException e) {
LogUtils.logException(e);
} catch (BiffException e) {
LogUtils.logException(e);
} finally {
try {
if (wbook != null) {
wbook.write();
wbook.close();
}
if (os != null) {
os.flush();
os.close();
}
if (is != null) {
is.close();
}
} catch (Exception e) {
LogUtils.logException(e);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: