springmvc 导出excel
http://blog.csdn.net/wlsyn/article/details/10195193
package com.tuling.view; import java.io.OutputStream; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.springframework.web.servlet.view.document.AbstractExcelView; public class ViewExcel extends AbstractExcelView { @Override public void buildExcelDocument(Map<String, Object> obj, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { String filename = "message.xls";// 设置下载时客户端Excel的名称 // filename = StringUtils.encodeFilename(filename, request);//处理中文文件名 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + filename); OutputStream ouputStream = response.getOutputStream(); workbook.write(ouputStream); ouputStream.flush(); ouputStream.close(); } }
controller
@RequestMapping(value = "export") public ModelAndView exportExcel(ModelMap model, HttpServletRequest request, HttpServletResponse response) { ViewExcel viewExcel = new ViewExcel(); Map<String, Object> obj = null; // 获取数据库表生成的workbook HSSFWorkbook workbook = new HSSFWorkbook(); List<Message> list = messageMapper.selectAll(); // excel文件名 try { HSSFSheet sheet = workbook.createSheet("消息反馈"); // workbook.setSheetName(0,sheetName,HSSFWorkbook..ENCODING_UTF_16); HSSFRow row = sheet.createRow((short) 0); HSSFCell cell = null; // 写入各个字段的名称 cell = row.createCell(0); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue("名称"); cell = row.createCell(1); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue("公司"); int iRow = 1; for (Message message : list) { // 写入各条记录,每条记录对应Excel中的一行 row = sheet.createRow((short) iRow); cell = row.createCell(0); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(message.getName()); cell = row.createCell(1); cell.setCellType(HSSFCell.CELL_TYPE_STRING); cell.setCellValue(message.getCompany()); iRow++; } } catch (Exception e) { e.printStackTrace(); } try { viewExcel.buildExcelDocument(obj, workbook, request, response); } catch (Exception e) { e.printStackTrace(); } return new ModelAndView(viewExcel, model); }
处理一下中文
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String filename = format.format(new Date())+"消息反馈.xls";// 设置下载时客户端Excel的名称 // filename = StringUtils.encodeFilename(filename, request);//处理中文文件名 filename = URLEncoder.encode(filename, "UTF-8");
设置表格的列宽
sheet.setColumnWidth(2, 10000);