導出以前對數據進行過濾、排序、分組等,到時候動態的傳進去就能夠了,實在很是的方便,廢話很少說,直接上代碼:
java
package com.yingchao.kgou.controller; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; public class ExcelStyle { public static HSSFCellStyle setHeadStyle(HSSFWorkbook workbook ,HSSFCellStyle style) { style.setFillForegroundColor(HSSFColor.SKY_BLUE.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); return style; } public static HSSFCellStyle setbodyStyle(HSSFWorkbook workbook ,HSSFCellStyle style2) { style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成字體 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 把字體應用到當前的樣樣式 style2.setFont(font2); return style2; } }
package com.yingchao.kgou.controller; import java.io.FileOutputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; 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.springframework.stereotype.Controller; import com.yingchao.kgou.bean.ExcelAnnotation; import com.yingchao.kgou.entity.Item; @Controller public class ExportExcel<T> { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化日期 /** * 導出excel * @param title標題 * @param dataset集合 * @param out輸出流 * @return * @throws Exception */ /** * * @param title 標題 * @param dataset 集合 * @param out 輸出流 */ public void exportExcel(String title, Collection<T> dataset, OutputStream out) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //格式化日期 // 聲明一個工做薄 try { //首先檢查數據看是不是正確的 Iterator<T> its = dataset.iterator(); if(dataset==null||!its.hasNext()||title==null||out==null) { throw new Exception("傳入的數據不對!"); } //取得實際泛型類 T ts = (T) its.next(); Class tCls = ts.getClass(); HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(title); // 設置表格默認列寬度爲20個字節 sheet.setDefaultColumnWidth(20); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設置標題樣式 style = ExcelStyle.setHeadStyle(workbook, style); // 獲得全部字段 Field filed[] = ts.getClass().getDeclaredFields(); // 標題 List<String> exportfieldtile = new ArrayList<String>(); // 導出的字段的get方法 List<Method> methodObj = new ArrayList<Method>(); // 遍歷整個filed for (int i = 0; i < filed.length; i++) { Field f = filed[i]; ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class); // 若是設置了annottion if (exa != null) { String exprot = exa.exportName(); // 添加到標題 exportfieldtile.add(exprot); // 添加到須要導出的字段的方法 String fieldname = f.getName(); String getMethodName = "get" + fieldname.substring(0, 1).toUpperCase() + fieldname.substring(1); Method getMethod = tCls.getMethod(getMethodName,new Class[] {}); methodObj.add(getMethod); } } // 產生表格標題行 HSSFRow row = sheet.createRow(0); for (int i = 0; i < exportfieldtile.size(); i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(exportfieldtile.get(i)); cell.setCellValue(text); } int index = 0; // 循環整個集合 its = dataset.iterator(); while (its.hasNext()) { //從第二行開始寫,第一行是標題 index++; row = sheet.createRow(index); T t = (T) its.next(); for (int k = 0; k < methodObj.size(); k++) { HSSFCell cell = row.createCell(k); Method getMethod=methodObj.get(k); Object value = getMethod.invoke(t, new Object[] {}); String textValue = getValue(value); cell.setCellValue(textValue); } } workbook.write(out); } catch (Exception e) { e.printStackTrace(); } } @SuppressWarnings({ "static-access" }) private String getValue(Object value) throws ParseException{ String textValue = ""; if(null == value){ return textValue; } if(value instanceof Boolean){ boolean bValue = (Boolean)value; textValue = "是"; if(!bValue){ textValue="否"; } }else if(value instanceof GregorianCalendar){ GregorianCalendar calendar = (GregorianCalendar)value; Date d = calendar.getTime(); textValue = sdf.format(d); }else{ textValue = value.toString(); } return textValue; } @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { //構造一個模擬的List來測試,實際使用時,這個集合是從數據庫中查出來的 List<Item> list = new ArrayList<Item>(); for (int i = 0; i < 10; i++) { Item item = new Item(); item.setTitle("商品"+i); item.setItemcode(String.valueOf(i)); item.setItemdesc("描述"+i); item.setCreated(Calendar.getInstance()); item.setDelistTime(Calendar.getInstance()); item.setListTime(Calendar.getInstance()); item.setModified(Calendar.getInstance()); item.setPrice(100d); item.setMarketprice(100d); item.setSellprice(100d); item.setScore(5f); item.setItempoint(1000); item.setIsTiming(Boolean.TRUE); item.setStorecount(Long.valueOf(i)); item.setAdminUid(Long.valueOf(i)); item.setAdminUpt(Long.valueOf(i)); item.setPicUrl("ff"); item.setState(i); list.add(item); } //構造輸出對象,能夠從response輸出,直接向用戶提供下載 OutputStream out = new FileOutputStream("E:\\testOne.xls"); //開始時間 Long l = System.currentTimeMillis(); //注意 new ExportExcel().exportExcel("測試",list, out); out.close(); //結束時間 Long s = System.currentTimeMillis(); System.out.println("總共耗時:"+(s-l)); } }
package com.yingchao.kgou.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import com.yingchao.kgou.bean.ExcelAnnotation; import com.yingchao.kgou.entity.Item; public class ImportExcel<T> { private Class<T> classzz; public ImportExcel(Class<T> classzz){ this.classzz=classzz; } /** * 導入excel * @param file * @param pattern * @return */ public Collection<T> importExcel(InputStream in,String...pattern){ Collection<T> dist = new ArrayList<T>(); try { /* * 類反射獲得調用方法 */ //獲得目標類的全部字段列表 Field[] field = classzz.getDeclaredFields(); //將全部標有annotation的字段,也就是容許導入數據的字段,放入到一箇中 Map fieldMap = new HashMap(); //循環讀取全部字段 for (int i = 0; i < field.length; i++) { Field f = field[i]; //獲得單個字段上的Annotation ExcelAnnotation exa = f.getAnnotation(ExcelAnnotation.class); //若是標識了Annotation的話 if(null != exa){ //構造設置了Annotation的字段的setter方法 String fieldName = f.getName(); String setMethodName = "set"+fieldName.substring(0,1).toUpperCase() +fieldName.substring(1); //構造調用的method Method method = classzz.getMethod(setMethodName, new Class[]{ f.getType() }); //將這個method以annotation的名字爲key來存入 fieldMap.put(exa.exportName(), method); } } /* * excel的解析開始 */ //獲得工做表 HSSFWorkbook book = new HSSFWorkbook(in); //獲得第一頁 HSSFSheet sheet = book.getSheetAt(0); //獲得第一面的全部行 Iterator<Row> row = sheet.rowIterator(); /* * 標題解析 */ //獲得第一行,也就是標題行 Row title = row.next(); //獲得第一行的全部列 Iterator<Cell> cellTitle = title.cellIterator(); //將標題的文字內容放入到一個map中 Map titleMap = new HashMap(); //從標題的第一列開始 int i = 0; //循環全部的列 while(cellTitle.hasNext()){ Cell cell = cellTitle.next(); String value = cell.getStringCellValue(); titleMap.put(i, value); i++; } /* * 解析內容行 */ //用來格式化日期的DateFormat SimpleDateFormat sf; if (pattern.length < 1) { sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } else sf = new SimpleDateFormat(pattern[0]); while(row.hasNext()){ //標題下的第一行 Row rown = row.next(); //行的全部列 Iterator<Cell> cellBody = rown.cellIterator(); //獲得傳入類的實例 T tObject = classzz.newInstance(); int k = 0; //遍歷一行的列 while(cellBody.hasNext()){ Cell cell = cellBody.next(); //這裏獲得此列對應的標題 String titleString = (String)titleMap.get(k); //若是這一列的標題和類中的某一列的Annotation相同,那麼則調用此類的setter方法,進行設值 if(fieldMap.containsKey(titleString)){ Method setMethod = (Method)fieldMap.get(titleString); //獲得setter方法的參數 Type[] ts = setMethod.getGenericParameterTypes(); //只要一個參數 String xClass = ts[0].toString(); //判斷參數類型 if(xClass.equals("class java.lang.String")){ setMethod.invoke(tObject, cell.getStringCellValue()); }else if(xClass.equals("class java.util.Calendar")){ Calendar c = new GregorianCalendar(); Date d = sf.parse(cell.getStringCellValue()); c.setTime(d); setMethod.invoke(tObject, c); }else if(xClass.equals("class java.lang.Boolean")){ Boolean boolName = true; if(cell.getStringCellValue().equals("否")){ boolName = false; } setMethod.invoke(tObject, boolName); }else if(xClass.equals("class java.lang.Integer")){ setMethod.invoke(tObject, new Integer(cell.getStringCellValue())); }else if(xClass.equals("class java.lang.Long")){ setMethod.invoke(tObject, new Long(cell.getStringCellValue())); }else if(xClass.equals("class java.lang.Double")){ setMethod.invoke(tObject, new Double(cell.getStringCellValue())); } } //下一列 k++; } dist.add(tObject); } } catch (Exception e) { e.printStackTrace(); return null; } return dist; } public static void main(String[] args) throws FileNotFoundException { // ImportExcel<Item> test = new ImportExcel<Item>(Item.class); // File file = new File("E:\\testOne.xls"); // Long befor = System.currentTimeMillis(); // final List<Item> result = (ArrayList<Item>)test.importExcel(new FileInputStream(file)); // Long after = System.currentTimeMillis(); // System.out.println("這次操做共耗時:"+(after-befor)); // // new Thread(){ // public void run() { // for (int i = 0; i < result.size(); i++) { // final Item item = result.get(i); // System.out.println("導入的信息爲:"+item.getTitle()+"\t"+new SimpleDateFormat("yyyy-MM-ss HH:mm:ss").format(item.getListTime().getInstance().getTime())); // } // }; // }.start(); // } }