亲测可用
引入pom依赖
org.apache.poi poi 3.17
Excel导出工具类
import org.apache.poi.hssf.usermodel.*;import org.apache.poi.ss.usermodel.*;public class ExcelUtils { /** * 导出Excel * @param sheetName sheet名称 * @param title 标题 * @param values 内容 * @param wb HSSFWorkbook对象 * @return */ public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){ // 第一步,创建一个HSSFWorkbook,对应一个Excel文件 if(wb == null){ wb = new HSSFWorkbook(); } // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet HSSFSheet sheet = wb.createSheet(sheetName); sheet.setColumnWidth(1,30*256); sheet.setColumnWidth(5,30*256); sheet.setColumnWidth(6,20*256); sheet.setColumnWidth(8,20*256); // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制 HSSFRow row = sheet.createRow(0); row.setHeightInPoints(20); // 第四步,创建单元格,并设置值表头 设置表头居中 HSSFCellStyle style =(HSSFCellStyle) wb.createCellStyle(); style.setVerticalAlignment(VerticalAlignment.CENTER); HSSFFont font = wb.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) 10); style.setFont(font); style.setWrapText(true); //声明列对象 HSSFCell cell = null; //创建标题 for(int i=0;i
控制器代码
@Controller@RequestMapping(value = "/report")public class ReportFormController extends BaseController { @Resource(name = "reportService") private ReportManager reportService; /** * 导出报表 * @return */ @RequestMapping(value = "/export") @ResponseBody public void export(HttpServletRequest request,HttpServletResponse response) throws Exception { //获取数据 Listlist = reportService.bookList(page); //excel标题 String[] title = {"名称","性别","年龄","学校","班级"}; //excel文件名 String fileName = "学生信息表"+System.currentTimeMillis()+".xls"; //sheet名 String sheetName = "学生信息表"; String[][] content = new String[list.size()][]; for (int i = 0; i < list.size(); i++) { content[i] = new String[title.length]; PageData obj = list.get(i); content[i][0] = obj.get("stuName").tostring(); content[i][1] = obj.get("stuSex").tostring(); content[i][2] = obj.get("stuAge").tostring(); content[i][3] = obj.get("stuSchoolName").tostring(); content[i][4] = obj.get("stuClassName").tostring(); } //创建HSSFWorkbook HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null); //响应到客户端 try { this.setResponseHeader(response, fileName); OutputStream os = response.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } //发送响应流方法 public void setResponseHeader(HttpServletResponse response, String fileName) { try { try { fileName = new String(fileName.getBytes(),"ISO8859-1"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.setContentType("application/octet-stream;charset=ISO8859-1"); response.setHeader("Content-Disposition", "attachment;filename="+ fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } }}