1、数据bean
/** * Excel Bean * @author rubekid * */ public class ExcelBean { private String name; private String sheetName; private String[] titles; private List<String[]> dataList; private boolean headBold = true; private int columnWidth = 6000; public ExcelBean(String name, String sheetName, String[] titles){ this.name = name; this.sheetName = sheetName; this.titles = titles; this.dataList = new ArrayList<String[]>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSheetName() { return sheetName; } public void setSheetName(String sheetName) { this.sheetName = sheetName; } public String[] getTitles() { return titles; } public void setTitles(String[] titles) { this.titles = titles; } public List<String[]> getDataList() { return dataList; } public void setDataList(List<String[]> dataList) { this.dataList = dataList; } public boolean isHeadBold() { return headBold; } public void setHeadBold(boolean headBold) { this.headBold = headBold; } public int getColumnWidth() { return columnWidth; } public void setColumnWidth(int columnWidth) { this.columnWidth = columnWidth; } public void add(String[] data){ this.dataList.add(data); } }
2、工具类
/** * excel 工具类 * @author rubekid * */ public class ExcelUtils { public static void export( ExcelBean excelBean) throws Exception{ HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet(excelBean.getSheetName()); HSSFRow row = sheet.createRow(0); //设置样式 HSSFCellStyle style = wb.createCellStyle(); if(excelBean.isHeadBold()){ HSSFFont headfont = wb.createFont(); headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setFont(headfont); } HSSFCell cell; String[] titles = excelBean.getTitles(); for(int i=0; i < titles.length; i++){ cell= row.createCell(i); cell.setCellValue(titles[i]); cell.setCellStyle(style); sheet.setColumnWidth(i, excelBean.getColumnWidth()); } int rowNumber = 1; for(String[] data : excelBean.getDataList()){ row = sheet.createRow(rowNumber ++ ); for(int j=0; j<data.length; j ++){ cell = row.createCell(j); cell.setCellValue(data[j]); } } HttpServletResponse response = Struts2Utils.getResponse(); response.setContentType("application/octet-stream;charset=utf-8"); response.setCharacterEncoding("utf-8"); String filename = excelBean.getName(); filename = new String(filename.replaceAll("\\s|;", "").getBytes("gbk"), "ISO8859-1"); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + filename); OutputStream ouputStream = response.getOutputStream(); wb.write(ouputStream); ouputStream.flush(); ouputStream.close(); } }
3、Demo
String[] titles = {"姓名", "年龄", "性别", "身高"}; ExcelBean excelBean = new ExcelBean("成员.xls", "少儿组", titles); excelBean.add(new String[]{"王仔", "10", "男", "120"}); excelBean.add(new String[]{"王妞", "9", "女", "110"}); ExcelUtils.export(excelBean);
时间: 2024-11-05 13:45:22