赞
踩
excel工具类
import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; 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.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * excel工具类 * */ public class ExcelUtils { /** * 下载excel文档到客户端 * @param response * @param hw */ public static void uploadExcel(HttpServletResponse response,HSSFWorkbook hw) { ByteArrayOutputStream fos = null; byte[] retArr = null; try { fos = new ByteArrayOutputStream(); hw.write(fos); retArr = fos.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } OutputStream os = null; try { os = response.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } try { response.reset(); response.setHeader("Content-Disposition", "attachment; filename="+"excel"+".xls");//要保存的文件名 response.setContentType("application/octet-stream; charset=utf-8"); try { os.write(retArr); } catch (IOException e) { e.printStackTrace(); } try { os.flush(); } catch (IOException e) { e.printStackTrace(); } } finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 生成excel * @param data 数据集合 * @param path 输出路径 */ public static HSSFWorkbook createExcel(String sheetName,String sheetTitleName,List<?> data) { // 创建workbook HSSFWorkbook wb = new HSSFWorkbook(); // 创建sheet Sheet sheet = wb.createSheet(sheetName); // 创建表头行 Row row = sheet.createRow(0); Cell oneCell = row.createCell(0); oneCell.setCellValue(sheetTitleName); //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列 sheet.addMergedRegion(new CellRangeAddress(0,0,0,9)); // 创建单元格样式 HSSFCellStyle style = wb.createCellStyle(); // 获取实体所有属性 Field[] fields = data.get(0).getClass().getDeclaredFields(); // 列索引 int index = 0; // 列名称 String name = ""; // 是否日期类型 boolean isDate = false; // 转换的日期格式 String dateFormat = ""; ExcelAnnotation ExcelAnnotation; // 创建表头 Row row1 = sheet.createRow(1); for (Field f : fields) { // 是否是注解 if (f.isAnnotationPresent(ExcelAnnotation.class)) { // 获取注解 ExcelAnnotation = f.getAnnotation(ExcelAnnotation.class); // 获取列索引 index = ExcelAnnotation.columnIndex(); // 列名称 name = ExcelAnnotation.columnName(); // 创建单元格 creCell(row1, index, name, style); } } // 行索引 因为表头已经设置,索引行索引从2开始 int rowIndex = 2; for (Object obj : data) { // 创建新行,索引加1,为创建下一行做准备 row = sheet.createRow(rowIndex++); for (Field f : fields) { // 设置属性可访问 f.setAccessible(true); // 判断是否是注解 if (f.isAnnotationPresent(ExcelAnnotation.class)) { // 获取注解 ExcelAnnotation = f.getAnnotation(ExcelAnnotation.class); index = ExcelAnnotation.columnIndex(); isDate = ExcelAnnotation.isDate(); try { // 创建单元格 f.get(obj)从obj对象中获取值设置到单元格中 if(isDate) { dateFormat = ExcelAnnotation.dateFormat(); creCell(row, index, UtilTools.getNewDateFormat((Date) f.get(obj),dateFormat), style); }else { creCell(row, index, String.valueOf(f.get(obj)), style); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } return wb; } /** * 生成excel文件直接保存到客户端指定文件夹下 * @param data 数据集合 * @param path 输出路径 */ public static void createExcelFile(String sheetName,String sheetTitleName,List<?> data, String path) { File file = new File(path); // 创建workbook HSSFWorkbook wb = new HSSFWorkbook(); // 创建sheet Sheet sheet = wb.createSheet(sheetName); // 创建表头行 Row row = sheet.createRow(0); Cell oneCell = row.createCell(0); oneCell.setCellValue(sheetTitleName); //合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列 sheet.addMergedRegion(new CellRangeAddress(0,0,0,9)); // 创建单元格样式 HSSFCellStyle style = wb.createCellStyle(); // 获取实体所有属性 Field[] fields = data.get(0).getClass().getDeclaredFields(); // 列索引 int index = 0; // 列名称 String name = ""; // 是否日期类型 boolean isDate = false; // 转换的日期格式 String dateFormat = ""; ExcelAnnotation ExcelAnnotation; // 创建表头 Row row1 = sheet.createRow(1); for (Field f : fields) { // 是否是注解 if (f.isAnnotationPresent(ExcelAnnotation.class)) { // 获取注解 ExcelAnnotation = f.getAnnotation(ExcelAnnotation.class); // 获取列索引 index = ExcelAnnotation.columnIndex(); // 列名称 name = ExcelAnnotation.columnName(); // 创建单元格 creCell(row1, index, name, style); } } // 行索引 因为表头已经设置,索引行索引从2开始 int rowIndex = 2; for (Object obj : data) { // 创建新行,索引加1,为创建下一行做准备 row = sheet.createRow(rowIndex++); for (Field f : fields) { // 设置属性可访问 f.setAccessible(true); // 判断是否是注解 if (f.isAnnotationPresent(ExcelAnnotation.class)) { // 获取注解 ExcelAnnotation = f.getAnnotation(ExcelAnnotation.class); index = ExcelAnnotation.columnIndex(); isDate = ExcelAnnotation.isDate(); try { // 创建单元格 f.get(obj)从obj对象中获取值设置到单元格中 if(isDate) { dateFormat = ExcelAnnotation.dateFormat(); creCell(row, index, UtilTools.getNewDateFormat((Date) f.get(obj),dateFormat), style); }else { creCell(row, index, String.valueOf(f.get(obj)), style); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(file); wb.write(outputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //释放资源 try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 读取excel文件,并把读取到的数据封装到clazz中 * * @param path * 文件路径 * @param clazz * 实体类 * @return 返回clazz集合 */ @SuppressWarnings("resource") public static <T extends Object> List<T> importExcelFile(String path, Class<T> clazz) { // 存储excel数据 List<T> list = new ArrayList<T>(); FileInputStream is = null; try { is = new FileInputStream(new File(path)); } catch (FileNotFoundException e1) { throw new RuntimeException("文件路径异常"); } Workbook wookbook = null; // 根据excel文件版本获取工作簿 if (path.endsWith(".xls")) { wookbook = xls(is); } else if (path.endsWith(".xlsx")) { wookbook = xlsx(is); } else { throw new RuntimeException("文件出错,非excel文件"); } // 得到一个工作表 Sheet sheet = wookbook.getSheetAt(0); // 获取行总数 int rows = sheet.getLastRowNum() + 1; Row row; // 获取类所有属性 Field[] fields = clazz.getDeclaredFields(); T obj = null; int coumnIndex = 0; Cell cell = null; ExcelAnnotation ExcelAnnotation = null; for (int i = 2; i < rows; i++) { // 获取excel行 row = sheet.getRow(i); try { // 创建实体 obj = clazz.newInstance(); for (Field field : fields) { // 设置属性可访问 field.setAccessible(true); // 判断是否是注解 if (field.isAnnotationPresent(ExcelAnnotation.class)) { // 获取注解 ExcelAnnotation = field.getAnnotation(ExcelAnnotation.class); // 获取列索引 coumnIndex = ExcelAnnotation.columnIndex(); // 获取单元格 cell = row.getCell(coumnIndex); /*设置cell值开始*/ switch (cell.getCellType()) { //数值类型 case Cell.CELL_TYPE_NUMERIC:{ // Date类型 if ( HSSFDateUtil.isCellDateFormatted(cell) ){ Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue()); if ( field.getType()==Date.class ) {//Date 类型接收 Date类型 field.set ( obj,date ); }else if ( field.getType()==String.class ) {//String 类型 接收 Date类型 try { field.set ( obj , new SimpleDateFormat("yyyy-MM-dd").parse(cell.getStringCellValue() ) ); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } } else { //纯数值 if ( field.getType()==Integer.class ) {//Integer 类型接收 纯数值 String str = cell.toString(); //去掉 结尾为.0的情况 正常小数 不会去掉有精度意义的小数 if ( str!=null && !"".equals(str.trim()) ) { String []strs = str.split("\\."); if ( strs.length > 1 && "0".equals(strs[1]) ) { str=strs[0]; } } field.set(obj, Integer.parseInt(str) ) ; } else if ( field.getType()==String.class ) { //String 类型接收 纯数值 field.set(obj, String.valueOf( cell.getNumericCellValue() ) ) ; } } break; } // 字符串类型 case Cell.CELL_TYPE_STRING : { if ( field.getType() == Date.class ) { //Data类型接收String Date date = null; try { date = new SimpleDateFormat("yyyy-MM-dd").parse(cell.getStringCellValue()); } catch (ParseException e) { e.printStackTrace(); } field.set(obj,date); } else if ( field.getType()==Integer.class ) { //Integer 类型接收 String field.set(obj,Integer.parseInt(cell.getStringCellValue())); } else { field.set(obj,cell.getStringCellValue()); } break; } //空值的情况 可以抛异常 也可以 设空值 case Cell.CELL_TYPE_BLANK : { field.set(obj,null); break; } } /*设置cell值结束*/ } } // 添加到集合中 list.add(obj); } catch (InstantiationException e1) { e1.printStackTrace(); } catch (IllegalAccessException e1) { e1.printStackTrace(); } } try { is.close(); } catch (IOException e) { e.printStackTrace(); } return list; } /** * 创建单元格 * * @param row * @param c * @param cellValue * @param style */ private static void creCell(Row row, int c, String cellValue, CellStyle style) { Cell cell = row.createCell(c); cell.setCellValue(cellValue); cell.setCellStyle(style); } /** * 对日期类型进行格式化 * * @param d * @param fmat */ public static String getNewDateFormat(Date d,String fmat) { String newDate=""; if(null!=d) { DateFormat df=new SimpleDateFormat(fmat); newDate=df.format(d); } return newDate; } /** * 对excel 2003处理 */ private static Workbook xls(InputStream is) { try { // 得到工作簿 return new HSSFWorkbook(is); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 对excel 2007处理 */ private static Workbook xlsx(InputStream is) { try { // 得到工作簿 return new XSSFWorkbook(is); } catch (IOException e) { e.printStackTrace(); } return null; } }
创建自定义注解
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * 定义excel描述注解 * */ @Retention(RetentionPolicy.RUNTIME) public @interface ExcelAnnotation { /** * 列索引 * @return */ public int columnIndex() default 0; /** * 列名 * @return */ public String columnName() default ""; /** * 是否日期类型 * @return */ public boolean isDate() default false; /** * 日期字符格式 * @return */ public String dateFormat() default ""; }
在需要导出的列上加自定义注解
public class UserBean { @ExcelAnnotation(columnIndex=0,columnName="序号") private Integer user_id; @ExcelAnnotation(columnIndex=1,columnName="部门id") private Integer dept_id; @ExcelAnnotation(columnIndex=2,columnName="用户名") private String user_account; @ExcelAnnotation(columnIndex=3,columnName="登录密码") private String user_password; @ExcelAnnotation(columnIndex=4,columnName="姓名") private String user_name; @ExcelAnnotation(columnIndex=5,columnName="头像") private String img; @ExcelAnnotation(columnIndex=6,columnName="年龄") private Integer user_age; @ExcelAnnotation(columnIndex=7,columnName="性别") private String user_sex; @ExcelAnnotation(columnIndex=8,columnName="地址") private String user_address; @ExcelAnnotation(columnIndex=9,columnName="生日",isDate=true,dateFormat="yyyy-MM-dd") @DateTimeFormat(pattern="yyyy-MM-dd") private Date user_birth; @ExcelAnnotation(columnIndex=10,columnName="电话") private String user_phone; @ExcelAnnotation(columnIndex=11,columnName="邮箱") private String email; @ExcelAnnotation(columnIndex=12,columnName="最后登录时间",isDate=true,dateFormat="yyyy-MM-dd hh:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd hh:mm:ss") private Date reg_time; private String dept_name; private String birthStr; private Integer role_id; private String mon; private int num;
导出excel
public void ExportUserList(HttpServletResponse response) {
List<UserBean> userList = userDao.queryUserList();
response.setContentType("text/html,charset=utf-8");
HSSFWorkbook hw = ExcelUtils.createExcel("用户信息表","用户信息表",userList);
//将excel的下载
ExcelUtils.uploadExcel(response,hw);
}
导入excel
public Map<String,Object> importExcel(MultipartFile file) { Map<String,Object>map=new HashMap<String, Object>(); String filename = file.getOriginalFilename(); if(filename.endsWith(".xls") || filename.endsWith(".xlsx")) { String originUrl="D:\\excelTest"; // 起个新名称,绝对不能重复 -> UUID : universe unique id String uuid = UUID.randomUUID().toString(); // 新名称 String newName = uuid + filename.substring(filename.lastIndexOf(".")); String filePath = originUrl + "/" + newName; File f = new File(filePath); try { file.transferTo(f); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } int x=0,y=0,sum=0; boolean flag=false; List<UserBean> userList = ExcelUtils.importExcelFile(filePath, UserBean.class); f.delete(); y=userList.size(); for(UserBean u : userList){ List<UserBean> user=userDao.getUserByAccount(u.getUser_account()); if(user!=null&&user.size()>0){ x++; }else{ int i=userDao.saveUser(u); sum+=i; } } if(sum==(y-x)){ flag=true; } map.put("msg", "共有"+y+"条数据,成功导入"+sum+"条数据,登陆账号重名的数据有"+x+"条"); map.put("flag", flag); }else { map.put("msg", "请上传正确格式的excel文档"); map.put("flag", false); } return map; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。