Posted on 2011-02-22 17:48
非洲小白脸 阅读(4553)
评论(0) 编辑 收藏 所属分类:
其他资源 、
excel word + macro
public ActionForward export(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String checkBoxValueList = request.getParameter("ckv");
if(!CommonUtil.isNotNullorEmtry(checkBoxValueList)) {
this.saveMessages(request, "export.fail");
return mapping.findForward("export.fail");
}
List<Order> listOrder = orderService.exportOrderList(checkBoxValueList);
try {
ServletOutputStream os = response.getOutputStream();
response.reset();
String fileName = new String("订单列表".getBytes("gb2312"), "ISO8859-1") +".xls";
response.setHeader("Content-disposition", "attachment; filename="+ fileName);
response.setContentType("application/msexcel");
String filePath = request.getSession().getServletContext().getRealPath("/excel/model/order.xls");
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(filePath));
try {
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row;
HSSFCell cell = null;
int rownum = 3;
HSSFCellStyle style = this.getStyle(workbook);
Iterator<Order> it = listOrder.iterator();
Order order = null;
while(it.hasNext()) {
order = new Order();
order = it.next();
row = sheet.createRow(rownum);
myCreateCell(1, String.valueOf(rownum-2), row, cell, style);
myCreateCell(2, order.getAdName(), row, cell, style);
myCreateCell(3, order.getSmallAreaName(), row, cell, style);
rownum++;
}
workbook.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void myCreateCell(int cellnum, String value, HSSFRow row, HSSFCell cell, HSSFCellStyle style) {
cell = row.createCell((short) cellnum);
cell.setCellValue(new HSSFRichTextString(value));
cell.setCellStyle(style);
}
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 10);
font.setFontName("宋体");
HSSFCellStyle style = workbook.createCellStyle();
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
style.setFont(font);
style.setWrapText(false);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
EXCEL模板加载出错的问题:
可能是因为模板中某些格式存在问题,或者模板中存在EXCEL的某些高级功能,【POI】无法加载导致出错。
解决办法:自己一步步从最简单的excel文件开始,绘制模板。