工作需要生成excel并下载。
jsp:<a href="${ctx}/device/dvbg/outExcelbg" class="data_input_bg">导出</a>
controler:
/*
* 生成excel
*/
@RequestMapping(value = "/outExcelbg", method = RequestMethod.GET)
public ModelAndView outExcelbg(HttpServletRequest request,HttpServletResponse response) throws IOException{
JSONObject ret=new JSONObject();
List<Dvbgdata> list=bgService.getBgdata((Ps) getSession().getAttribute(CURRENT_USER));
ExcelUtil.outExcelbg(request.getRealPath("/upload").toString(),list);
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String ctxPath = request.getSession().getServletContext().getRealPath("/upload")
+ "\\" + "xls\\";
String downLoadPath = ctxPath + "bg_temp.xls";
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename="
+ new String("bg_temp.xls".getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;
}
util:
public static void outExcelbg(String pathString,List<Dvbgdata> bgdatas){
try{
WritableWorkbook book = Workbook.createWorkbook(new File(pathString+"/xls/bg_temp.xls"));
// 生成名为“第一页”的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet( "血糖表" , 0 );
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
WritableCell cell=null;
// 将定义好的单元格添加到工作表中
Label label1=new Label(0,0,"时间");
Label label2=new Label(1,0,"血糖(mmol/l)");
Label label3=new Label(2,0,"设备号");
Label label4=new Label(3,0,"详情");
sheet.addCell(label1);
sheet.addCell(label2);
sheet.addCell(label3);
sheet.addCell(label4);
int length=bgdatas.size();
int i=1;
for(Dvbgdata dvbgdata : bgdatas){
Label label01=new Label(0, i, DateUtil.dateToString(dvbgdata.getMeterdate()));
Label label02=new Label(1, i, dvbgdata.getBg().toString());
Label label03=new Label(2, i, dvbgdata.getDevicesn());
Label label04=new Label(3, i,WarningsUtil.getBg(Double.parseDouble(dvbgdata.getBg().toString())));
sheet.addCell(label01);
sheet.addCell(label02);
sheet.addCell(label03);
sheet.addCell(label04);
System.out.println(dvbgdata.getBg());
i++;
if(i>length){
break;
}
}
// 写入数据并关闭文件
book.write();
book.close();
}catch(Exception e) {
System.out.println(e);
}
}