在项目中,经常有导出Excel功能,一直都没有记文档,在再次使用时又是各种Googel,百度出Excel的方式千奇百怪,甚是头疼。因此,记录一下,
本方法需要导入的jar包:只是处理Excel,我们只需导入poi,poi-ooxml, poi-ooxml-schemas
前端页面请求方式:<a href="请求URL">导出Excel</a>
以下方式经本人亲自体验,项目在用:
@RequestMapping("/exportExcel")
public void exportExcel(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String[] fileds = { "UserName", "Consignee", "TelPhone", "Address", "Note" };
String[] title = { "用户名", "收件人", "电话", "地址", "备注" };
String fileName = "exportExcel.xls";
response.setHeader("Content-disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"), "ISO8859-1")); // 设置文件头编码格式
response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");// 设置类型
response.setHeader("Cache-Control", "no-cache");// 设置头
response.setDateHeader("Expires", 0);// 设置日期头
HSSFWorkbook book = new HSSFWorkbook();
HSSFSheet sheet = book.createSheet();
CellStyle cellStyle = book.createCellStyle();
cellStyle.setDataFormat(book.createDataFormat().getFormat("yyyy-MM-dd"));
// 设置Excel Title
HSSFRow row1 = sheet.createRow(0);
for (int i = 0; i < title.length; i++) {
sheet.setColumnWidth(i, 30 * 256);
// cellStyle.setBorderBottom(BorderStyle.DASH_DOT);
cellStyle.setAlignment(HorizontalAlignment.CENTER_SELECTION);
row1.setHeightInPoints(20);
HSSFCell cell = row1.createCell(i);
cell.setCellStyle(cellStyle);
cell.setCellValue(title[i]);
}
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map0 = new HashMap<String, Object>();
map0.put("UserName", "zhangsan");
map0.put("Consignee", "张三");
map0.put("TelPhone", "13314406781");
map0.put("Address", "China");
map0.put("Note", "这是张三");
list.add(map0);
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("UserName", "lisi");
map1.put("Consignee", "李四");
map1.put("TelPhone", "13814526584");
map1.put("Address", "China");
map1.put("Note", "这是李四");
list.add(map1);
if (list != null && list.size() > 0) {
int i = 1;
for (Map<String, Object> _m : list) {
Row row = sheet.createRow(i);
i++;
for (int j = 0; j < fileds.length; j++) {
Cell cell = row.createCell(j);
cell.setCellStyle(cellStyle);
row.setHeightInPoints(20);
cell.setCellValue("");
if ("CreateTime".equals(fileds[j]) || "UpdateTime".equals(fileds[j])) {
if (fileds[j] != null) {
cell.setCellValue(DateTimeUtil.formatDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(_m.get(fileds[j]).toString()), "yyyy-MM-dd HH:mm:ss"));
}
} else {
cell.setCellValue(_m.get(fileds[j]) == null ? "" : _m.get(fileds[j]).toString());
}
}
}
}
book.write(response.getOutputStream());
response.getOutputStream().flush();
response.getOutputStream().close();
}