使用POI插件,提取导出excel的工具类
在网站的不同的模块都需要使用到导入导出excel的功能,我们就需要写一个通用的工具类ExcelUtil。
- 我的思路:
首先,导入和导出的Excel的文件格式固定:主标题,二级标题,数据行(姑且就这么叫),详细的见下图:
分析这张图发现在不同的模块场景使用时,这三大部分都是不同的,他们三者的样式也是不同的,所以需要在ExcelUtil类里面对这三大部分写不同的方法
其次是导入可能和导出的数据不同,所以二级标题,数据行的显示列数,和内容需要有用户指定,而不是javabean有多少字段就输出多少,何况在User这个javabean里面有两个
特殊的字段(//状态
public static String USER_STATE_VALID="1";
public static String USER_STATE_INVILID="2";)
因为他们既不存在数据库也不存在Excel,所以导入导出就不要和他们扯上半毛钱的关系。
另外在ExcelUtil里面对单元格的读取也被提取出来了做一个方法,
需要指出的是:由于不想维护User中关于性别的字段,我直接使用了String的类型,原因就在于我在Excel输出可不想显示true、false,为了单个Excel的某一字段的显示,我要修改我的通用ExcelUtil,而且改动的非常复杂(不失去通用性也不影响其他模块使用,要知道可能就仅仅这里我要转换一下true:男,false:女),就直接改javabean,收工搞定
不多说,上代码:
package com.itcast.core.utils; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; import net.sf.ehcache.hibernate.management.impl.BeanUtils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFName; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFCellUtil; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.ss.util.CellRangeAddress; public class ExcelUtil { private ExcelUtil() { } /** * 导出excel头部标题 * @param title * @param cellRangeAddressLength * @return */ public static HSSFWorkbook makeExcelHead(String title, int cellRangeAddressLength){ HSSFWorkbook workbook = new HSSFWorkbook(); HSSFCellStyle styleTitle = createStyle(workbook, (short)16); HSSFSheet sheet = workbook.createSheet(title); sheet.setDefaultColumnWidth(25); CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, cellRangeAddressLength); sheet.addMergedRegion(cellRangeAddress); HSSFRow rowTitle = sheet.createRow(0); HSSFCell cellTitle = rowTitle.createCell(0); // 为标题设置背景颜色 styleTitle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); styleTitle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); cellTitle.setCellValue(title); cellTitle.setCellStyle(styleTitle); return workbook; } /** * 设定二级标题 * @param workbook * @param secondTitles * @return */ public static HSSFWorkbook makeSecondHead(HSSFWorkbook workbook, String[] secondTitles){ // 创建用户属性栏 HSSFSheet sheet = workbook.getSheetAt(0); HSSFRow rowField = sheet.createRow(1); HSSFCellStyle styleField = createStyle(workbook, (short)13); for (int i = 0; i < secondTitles.length; i++) { HSSFCell cell = rowField.createCell(i); cell.setCellValue(secondTitles[i]); cell.setCellStyle(styleField); } return workbook; } /** * 插入数据 * @param workbook * @param dataList * @param beanPropertys * @return */ public static <T> HSSFWorkbook exportExcelData(HSSFWorkbook workbook, List<T> dataList, String[] beanPropertys) { HSSFSheet sheet = workbook.getSheetAt(0); // 填充数据 HSSFCellStyle styleData = workbook.createCellStyle(); styleData.setAlignment(HSSFCellStyle.ALIGN_CENTER); styleData.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); for (int j = 0; j < dataList.size(); j++) { HSSFRow rowData = sheet.createRow(j + 2); T t = dataList.get(j); for(int k=0; k<beanPropertys.length; k++){ Object value = BeanUtils.getBeanProperty(t, beanPropertys[k]); HSSFCell cellData = rowData.createCell(k); cellData.setCellValue(value.toString()); cellData.setCellStyle(styleData); } } return workbook; } /** * 使用批量导入方法时,请注意需要导入的Bean的字段和excel的列一一对应 * @param clazz * @param file * @param beanPropertys * @return */ public static <T> List<T> parserExcel(Class<T> clazz, File file, String[] beanPropertys) { // 得到workbook List<T> list = new ArrayList<T>(); try { Workbook workbook = WorkbookFactory.create(file); Sheet sheet = workbook.getSheetAt(0); // 直接从第三行开始获取数据 int rowSize = sheet.getPhysicalNumberOfRows(); if(rowSize > 2){ for (int i = 2; i < rowSize; i++) { T t = clazz.newInstance(); Row row = sheet.getRow(i); int cellSize = row.getPhysicalNumberOfCells(); for(int j=0; j<cellSize; j++){ Object cellValue = getCellValue(row.getCell(j)); org.apache.commons.beanutils.BeanUtils.copyProperty(t, beanPropertys[j], cellValue); } list.add(t); } } } catch (Exception e) { e.printStackTrace(); } return list; } /** * 通用的读取excel单元格的处理方法 * @param cell * @return */ private static Object getCellValue(Cell cell) { Object result = null; if (cell != null) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: result = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: //对日期进行判断和解析 if(HSSFDateUtil.isCellDateFormatted(cell)){ double cellValue = cell.getNumericCellValue(); result = HSSFDateUtil.getJavaDate(cellValue); } break; case Cell.CELL_TYPE_BOOLEAN: result = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_FORMULA: result = cell.getCellFormula(); break; case Cell.CELL_TYPE_ERROR: result = cell.getErrorCellValue(); break; case Cell.CELL_TYPE_BLANK: break; default: break; } } return result; } /** * 提取公共的样式 * @param workbook * @param fontSize * @return */ private static HSSFCellStyle createStyle(HSSFWorkbook workbook, short fontSize){ HSSFCellStyle style = workbook.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 创建一个字体样式 HSSFFont font = workbook.createFont(); font.setFontHeightInPoints(fontSize); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); style.setFont(font); return style; } }
如何调用:
@Override public void exportExcel(ServletOutputStream outputStream, List<User> userList) { try { HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("用户列表", 4); String[] secondTitles = {"用户名", "账号", "所属部门", "性别", "电子邮箱"}; HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles); String[] beanProperty = {"name","account","dept", "gender", "email"}; HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, userList, beanProperty); workbook.write(outputStream); } catch (IOException e) { e.printStackTrace(); } } @Override public void importExcel(File file) { String[] beanProperty = {"name","account","dept", "gender", "mobile", "email", "birthday"}; List<User> list = ExcelUtil.parserExcel(User.class, file, beanProperty); if(list.size() > 0){ for(User user : list){ user.setPassword("123456"); user.setState(User.USER_STATE_VALID); add(user); } } }
posted on 2015-09-27 18:24 liujie037 阅读(7052) 评论(0) 编辑 收藏 举报