Apache POI操作Excel导出JAVABEAN对象方法
生活随笔
收集整理的這篇文章主要介紹了
Apache POI操作Excel导出JAVABEAN对象方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
Apache POI操作Excel導出方法說明
Apache的POI組件是Java操作Microsoft Office辦公套件的強大API,其中對Word,Excel和PowperPoint都有支持,當然使用較多的還是Excel,因為Word和PowerPoint用程序動態操作的應用較少。本文主要介紹一下Excel的操作方法。
- HSSF?-?提供讀寫?Microsoft ExcelXLS格式檔案的功能。
- XSSF?-?提供讀寫?Microsoft ExcelOOXML XLSX格式檔案的功能。
- HWPF?-?提供讀寫?Microsoft WordDOC格式檔案的功能。
- HSLF?-?提供讀寫?MicrosoftPowerPoint格式檔案的功能。
- HDGF?-?提供讀?Microsoft Visio格式檔案的功能。
- HPBF?-?提供讀?MicrosoftPublisher格式檔案的功能。
- HSMF?-?提供讀?Microsoft Outlook格式檔案的功能。?
EXCEL單元格樣式設置:
// 創建字體 HSSFFont font = wb.createFont(); // 設置字體為紅色 font.setColor(HSSFFont.COLOR_RED); // 設置字體為粗體 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 創建單元格格式 HSSFCellStyle cellStyle= wb.createCellStyle(); // 設置字體 cellStyle.setFont(font); // 設置水平居中 cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 設置垂直靠下 cellStyle.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM); // 設置左邊框為雙線 cellStyle.setBorderLeft(CellStyle.BORDER_DOUBLE); // 設置背景色為藍色 cellStyle.setFillBackgroundColor(new HSSFColor.BLUE().getIndex()); // 設置前景色為黃色 cellStyle.setFillForegroundColor(new HSSFColor.YELLOW().getIndex());?
Excel導出:
第一種,利用JAVA反射導出: ? ?
POIExcelUtil 類:?
import?org.apache.poi.hssf.usermodel.HSSFWorkbook; import?org.apache.poi.ss.usermodel.Cell; import?org.apache.poi.ss.usermodel.CreationHelper; 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.xssf.usermodel.XSSFWorkbook;public?class?POIExcelUtil?{public?static?final?String?FILE_EXTENSION_XLS?=?"xls";public?static?final?String?FILE_EXTENSION_XLSX?=?"xlsx";/***?*?@param?Map*????????????<String,String>?maps?屬性表,成員屬性age為KEY,中文名稱為VALUE*?@param?List*????????????<T>?list?需要導出的數據列表對象*?@param?File*????????????file?指定輸出文件位置,只能導出excel2003以上版本*????????????*?@return?true?導出成功?false?導出失敗*/public?static?<T>?boolean?excelExport(Map<String,?String>?maps,?List<T>?list,?File?file)?{try?{Workbook?wb?=?null;String?filename?=?file.getName();String?type?=?filename.substring(filename.lastIndexOf(".")+1).toLowerCase();if?(type.equals(FILE_EXTENSION_XLS))?{wb?=?new?HSSFWorkbook();}if?(type.equals(FILE_EXTENSION_XLSX))?{wb?=?new?XSSFWorkbook();}CreationHelper?createHelper?=?wb.getCreationHelper();Sheet?sheet?=?wb.createSheet("sheet1");Set<String>?sets?=?maps.keySet();Row?row?=?sheet.createRow(0);int?i?=?0;//?定義表頭for?(Iterator<String>?it?=?sets.iterator();?it.hasNext();)?{String?key?=?it.next();Cell?cell?=?row.createCell(i++);cell.setCellValue(createHelper.createRichTextString(maps.get(key)));}//?填充表單內容System.out.println("--------------------100%");float?avg?=?list.size()?/?20f;int?count?=?1;for?(int?j?=?0;?j?<?list.size();?j++)?{T?p?=?list.get(j);Class?classType?=?p.getClass();int?index?=?0;Row?row1?=?sheet.createRow(j+1);for?(Iterator<String>?it?=?sets.iterator();?it.hasNext();)?{String?key?=?it.next();String?firstLetter?=?key.substring(0,?1).toUpperCase();//?獲得和屬性對應的getXXX()方法的名字String?getMethodName?=?"get"?+?firstLetter+?key.substring(1);//?獲得和屬性對應的getXXX()方法Method?getMethod?=?classType.getMethod(getMethodName,new?Class[]?{});//?調用原對象的getXXX()方法Object?value?=?getMethod.invoke(p,?new?Object[]?{});Cell?cell?=?row1.createCell(index++);cell.setCellValue(value.toString());}if?(j?>?avg?*?count)?{count++;System.out.print("I");}if?(count?==?20)?{System.out.print("I100%");count++;}}FileOutputStream?fileOut?=?new?FileOutputStream(file);wb.write(fileOut);fileOut.close();}?catch?(IOException?e)?{e.printStackTrace();return?false;}?catch?(SecurityException?e)?{e.printStackTrace();return?false;}?catch?(NoSuchMethodException?e)?{e.printStackTrace();return?false;}?catch?(IllegalArgumentException?e)?{e.printStackTrace();return?false;}?catch?(IllegalAccessException?e)?{e.printStackTrace();return?false;}?catch?(InvocationTargetException?e)?{e.printStackTrace();return?false;}return?true;} }?
第二種:利用JAVA反射和Annotation導出
POIExcelAnnotation 類:
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface POIExcelAnnotation {public String titleName(); }POIExcelUtil 類:
import org.apache.poi.hssf.usermodel.HSSFFont; 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.CreationHelper; import org.apache.poi.ss.usermodel.Font; 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.xssf.usermodel.XSSFWorkbook;public class POIExcelUtil {public static final String FILE_EXTENSION_XLS = "xls";public static final String FILE_EXTENSION_XLSX = "xlsx";/*** * @param sheetName sheet名稱* @param pojoClass POJO對象類* @param list 導出數據列表* @param file file 指定輸出文件* @return true 導出成功 false 導出失敗*/public static <T> boolean excelAnnotationExport(String sheetName ,Class<T> pojoClass,List<T> list, File file) {try {Workbook wb = null;String filename = file.getName();String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();if (type.equals(FILE_EXTENSION_XLS)) {wb = new HSSFWorkbook();}if (type.equals(FILE_EXTENSION_XLSX)) {wb = new XSSFWorkbook();}CreationHelper createHelper = wb.getCreationHelper();Sheet sheet = wb.createSheet(sheetName);// 標題 List<String> fieldTitle = new ArrayList<String>(); //方法列表,對應表頭List<Method> methodObj = new ArrayList<Method>(); // 得到所有字段 Field fileds[] = pojoClass.getDeclaredFields(); // 遍歷整個filed for (int i = 0; i < fileds.length; i++) { Field field = fileds[i]; POIExcelAnnotation annotation = field.getAnnotation(POIExcelAnnotation.class); // 如果設置了annottion if (annotation != null) { // 添加到標題 fieldTitle.add(annotation.titleName()); // 添加到需要導出的字段的方法 String fieldName = field.getName(); String firstLetter = fieldName.substring(0, 1).toUpperCase();// 獲得和屬性對應的getXXX()方法的名String getMethodName = "get" + firstLetter+ fieldName.substring(1);// 獲得和屬性對應的getXXX()方法Method getMethod = pojoClass.getMethod(getMethodName,new Class[] {}); methodObj.add(getMethod); } }//設置表頭粗體Font font = wb.createFont();font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);CellStyle style = wb.createCellStyle();style.setFont(font);//填充表頭內容Row row = sheet.createRow(0);for(int i=0;i<fieldTitle.size();i++){String title = fieldTitle.get(i);Cell cell = row.createCell(i);cell.setCellStyle(style);cell.setCellValue(createHelper.createRichTextString(title));}// 填充表單內容System.out.println("--------------------100%");float avg = list.size() / 20f;int count = 1;for (int j = 0; j < list.size(); j++) {T p = list.get(j);Row row1 = sheet.createRow(j+1); for (int k=0;k<methodObj.size();k++) {Method getMethod = methodObj.get(k);Object value = getMethod.invoke(p, new Object[] {});Cell cell = row1.createCell(k);cell.setCellValue(value.toString());}if (j > avg * count) {count++;System.out.print("I");}if (count == 20) {System.out.println("I100%");count++;}}FileOutputStream fileOut = new FileOutputStream(file);wb.write(fileOut);fileOut.close();} catch (IOException e) {e.printStackTrace();return false;} catch (SecurityException e) {e.printStackTrace();return false;} catch (NoSuchMethodException e) {e.printStackTrace();return false;} catch (IllegalArgumentException e) {e.printStackTrace();return false;} catch (IllegalAccessException e) {e.printStackTrace();return false;} catch (InvocationTargetException e) {e.printStackTrace();return false;}return true;} }調用方法截取代碼:
public static void main(String args[]){ List<JavaBean> demo = ****;Map<String,String>?maps?=?new?LinkedHashMap<String,String>();maps.put("uid",?"帳號");maps.put("cn",?"姓名");maps.put("dept",?"部門");maps.put("mail",?"郵箱");Properties?props?=?System.getProperties();String?USER_HOME?=?props.getProperty("user.home");File?file?=?new?File(USER_HOME?+?"/Desktop/excelExport.xlsx");POIExcelUtil.excelExport(maps,?demo , file); }?
Excel導入:
import org.apache.poi.hssf.usermodel.HSSFFont; 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.CreationHelper; import org.apache.poi.ss.usermodel.Font; 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.xssf.usermodel.XSSFWorkbook;public class POIExcelUtil {public static final String FILE_EXTENSION_XLS = "xls";public static final String FILE_EXTENSION_XLSX = "xlsx";@SuppressWarnings("unchecked")public static List importExcel(File file ){List list = new ArrayList();Workbook wb = null;String filename = file.getName();String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();if (type.equals(FILE_EXTENSION_XLS)) {wb = new HSSFWorkbook();}if (type.equals(FILE_EXTENSION_XLSX)) {wb = new XSSFWorkbook();}Sheet sheet = wb.getSheetAt(0);for(int i=1;i<sheet.getLastRowNum();i++){Row row = sheet.getRow(i);//以下代碼,根據需求自由變化for(int j=0;j<row.getLastCellNum();j++){Cell cell = row.getCell(j); list.add(cell.getRichStringCellValue().getString());}}return list;} }?
轉載于:https://my.oschina.net/u/154628/blog/262290
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的Apache POI操作Excel导出JAVABEAN对象方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安装并测试nvenc linux sdk
- 下一篇: CentOS安装rpm包时遇到Heade