导入导出Excel是我们开发管理系统中最常见的功能,因为在企业应用中各种财务数据,生产销售数据业务人员基本都是用Excel来处理的。导入导出Excel有许多实现方式,今天我们就用开源的POI组件来实现Excel的导入导出功能。
导出Excel代码如下:
package com.meinong.util; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; 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.HSSFColor; /** * 利用开源组件POI3.0.2动态导出EXCEL文档 * @author 堆代码 duidaima.com * @version v1.0 * @param <T> * 应用泛型,代表任意一个符合javabean风格的类 * 注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx() */ public class ExportExcel<T> { public void exportExcel(String title ,String[] headers,Collection<T> dataset, OutputStream out) { exportExcel(title, headers, dataset,"yyyy-MM-dd HH:mm:ss", out, new ArrayList<String>()); } public void exportExcel(String title ,String[] headers,Collection<T> dataset,String pattern, OutputStream out) { exportExcel(title, headers, dataset,pattern, out, new ArrayList<String>()); } public void exportExcel(String title ,String[] headers,String pattern,Collection<T> dataset, OutputStream out,String notExpStr) { List<String> li = new ArrayList<String>(); li.add(notExpStr); exportExcel(title, headers, dataset,pattern,out, li); } /** * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上 * * @param title * 表格标题名 * @param headers * 表格属性列名数组 * @param dataset * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的 * javabean属性的数据类型有基本数据类型及String,Date * @param out * 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中 * @param pattern * 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd HH:mm:ss" * @param List<String> notExpStrs 不导出字段 集合 * */ @SuppressWarnings("unchecked") public void exportExcel(String title, String[] headers, Collection<T> dataset, String pattern, OutputStream out,List<String> li) { // 声明一个工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一个表格 HSSFSheet sheet = workbook.createSheet(title); // 设置表格默认列宽度为20个字节 sheet.setDefaultColumnWidth(20); // 生成一个样式 HSSFCellStyle style = workbook.createCellStyle(); // 设置这些样式 style.setFillForegroundColor(HSSFColor.WHITE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 生成一个字体 HSSFFont font = workbook.createFont(); // font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字体应用到当前的样式 style.setFont(font); //生成数据区域样式 HSSFCellStyle style1 = workbook.createCellStyle(); // 设置这些样式 style1.setFillForegroundColor(HSSFColor.WHITE.index); // style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); // style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); // style1.setBorderLeft(HSSFCellStyle.BORDER_THIN); // style1.setBorderRight(HSSFCellStyle.BORDER_THIN); // style1.setBorderTop(HSSFCellStyle.BORDER_THIN); // 生成一个字体 // HSSFFont font1 = workbook.createFont(); // font.setColor(HSSFColor.VIOLET.index); // font.setFontHeightInPoints((short) 12); // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字体应用到当前的样式 // style.setFont(font); //----- // 产生表格标题行 HSSFRow row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } // 遍历集合数据,产生数据行 Iterator<T> it = dataset.iterator(); int index = 0; HSSFFont font3 = workbook.createFont(); while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值 Field[] fields = t.getClass().getDeclaredFields(); List<String> strFields = new ArrayList<String>(); for(Field f :fields){ if(!li.contains(f.getName())) strFields.add(f.getName()); } for (int i = 0; i < strFields.size(); i++) { HSSFCell cell = row.createCell(i); // cell.setCellStyle(style2); // Field field = fields[i]; String fieldName = strFields.get(i); String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { Class tCls = t.getClass(); Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); String textValue =null; // 判断值的类型后进行强制类型转换 if(value!=null){ if(value.toString().length()>=2) if(value.toString().substring(0, 2).equals("0E")) value = "0.00"; if (value instanceof Date) { style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); } else textValue = value.toString(); } //利用正则表达式判断textValue是否全部由数字组成 if (textValue != null) { Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { style1.setAlignment(HSSFCellStyle.ALIGN_RIGHT); // 是数字当作double处理 cell.setCellStyle(style1); cell.setCellValue(Double.parseDouble(textValue)); } else { HSSFRichTextString richString = new HSSFRichTextString( textValue); // font3.setColor(HSSFColor.BLUE.index); style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); richString.applyFont(font3); cell.setCellStyle(style1); cell.setCellValue(richString); } } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } try { workbook.write(out); workbook.close(); } catch (IOException e) { e.printStackTrace(); } } // private Field[] delNotExpStr(Field[] fields , String[] notExpStr){ // if(notExpStr==null) // return fields; // else{ // // return null; // } // // } }
总结:
以上就是我们在JAVA中基于POI开源组件实现Excel导出功能的代码讲解。POI是一款非常优秀且功能强大的Excel操作组件,支持各种复杂的生成Excel需求,强烈推荐在项目中使用。