效果以下:java
代碼以下:apache
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; 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.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.util.CellRangeAddress; /** * 使用該類時,肯定引入的poi相關的jar包 * Maven以下: * <!-- POI --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency> * @author Mr.wang * @date 2018/06/14 * */ public class ExcelUtils { public static void main(String[] args) throws IOException { List<String> title = Arrays.asList("姓名", "年齡", "生日", "郵箱"); List<List<String>> personInfos = new ArrayList<List<String>>(); List<String> person01 = Arrays.asList("Ben", "26", "1992-02-12", "ben@sina.com"); List<String> person02 = Arrays.asList("Tom", "27", "1993-08-18", "tom@sina.com"); List<String> person03 = Arrays.asList("Jack", "28", "1994-03-28", "jack@sina.com"); List<String> person04 = Arrays.asList("恩索", "29", "1995-01-09", "enso@sina.com"); personInfos.add(person01); personInfos.add(person02); personInfos.add(person03); personInfos.add(person04); File file = new File("D:/demo.xls"); //createExcelFile(title, personInfos, file, null); createExcelFileWithHead(title, personInfos, file, null, "我的信息表"); } /** * 由生成流的方法進一步封裝成生成excel(.xls)的文件 * @see #createExcelInStream(List, List, OutputStream, String) * @param title * @param listData * @param fileWithPathAndName * @param sheetName * @throws IOException */ public static void createExcelFile(List<String> title, List<List<String>> listData, File fileWithPathAndName, String sheetName) throws IOException { FileOutputStream fos=new FileOutputStream(fileWithPathAndName); createExcelInStream(title, listData, fos, sheetName); if(fos!=null) { fos.close(); } } /** * 由生成流的方法進一步封裝成生成excel(.xls)的文件 * @see #createExcelInStreamWithHead(List, List, OutputStream, String, String) * @param title * @param listData * @param fileWithPathAndName * @param sheetName * @param header * @throws IOException */ public static void createExcelFileWithHead(List<String> title, List<List<String>> listData, File fileWithPathAndName, String sheetName,String header) throws IOException { FileOutputStream fos=new FileOutputStream(fileWithPathAndName); createExcelInStreamWithHead(title, listData, fos, sheetName, header); if(fos!=null) { fos.close(); } } /** * create by Mr.wang 2018/06/14 * * 生成excel流(不帶表頭)。以xls爲後綴的文件,防止有些電腦不支持office07以上的 * * @param title * 標題 * @param listData * 數據內容 * @param outputStream * 輸出的流 * @param sheetName * 建立的sheet(不是文件)的名稱,若是有空,則採用sheet1做用默認的表名稱 * @throws IOException * * * example: * * List<String> title = Arrays.asList("姓名", "年齡", "生日", "郵箱"); List<List<String>> personInfos = new ArrayList<List<String>>(); List<String> person01 = Arrays.asList("Ben", "26", "1992-02-12", "ben@sina.com"); List<String> person02 = Arrays.asList("Tom", "27", "1993-08-18", "tom@sina.com"); List<String> person03 = Arrays.asList("Jack", "28", "1994-03-28", "jack@sina.com"); List<String> person04 = Arrays.asList("恩索", "29", "1995-01-09", "enso@sina.com"); personInfos.add(person01); personInfos.add(person02); personInfos.add(person03); personInfos.add(person04); File file = new File("D:/demo.xls"); FileOutputStream fos=new FileOutputStream(file); createExcelFile(title, personInfos, fos, null); ... * */ @SuppressWarnings("deprecation") public static void createExcelInStream(List<String> title, List<List<String>> listData, OutputStream outputStream, String sheetName) throws IOException { // 建立工做簿 HSSFWorkbook workBook = new HSSFWorkbook(); // 建立工做表 工做表的名字叫helloWorld if (sheetName == null || sheetName.length() == 0) { sheetName = "sheet1"; } HSSFSheet sheet = workBook.createSheet(sheetName); // 建立單元格,首先設置標題 HSSFFont fontTitle = workBook.createFont(); fontTitle.setBold(true); HSSFCellStyle titleStyle = workBook.createCellStyle(); titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); titleStyle.setFont(fontTitle); HSSFRow titleRow = sheet.createRow(0); for (int i = 0; i < title.size(); i++) { HSSFCell titleCol = titleRow.createCell(i, CellType.STRING); titleCol.setCellValue(title.get(i)); titleCol.setCellStyle(titleStyle); } sheet.autoSizeColumn(0); // 建立數據行 HSSFCellStyle dataStyle = workBook.createCellStyle(); dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); for (int i = 0; i < listData.size(); i++) { HSSFRow dataRow = sheet.createRow(i + 1); List<String> rowData = listData.get(i); for (int j = 0; j < rowData.size(); j++) { HSSFCell dataCol = dataRow.createCell(j, CellType.STRING); dataCol.setCellValue(rowData.get(j)); dataCol.setCellStyle(dataStyle); } sheet.autoSizeColumn(i); } HSSFRow firstRow = sheet.getRow(0); int lastCellNum = firstRow.getLastCellNum(); //爲了美觀,把全部的cell擴大1/2 for(int i=0;i<lastCellNum;i++) { int columnWidth = sheet.getColumnWidth(i); sheet.setColumnWidth(i, columnWidth+columnWidth*1/2); } workBook.write(outputStream); workBook.close();// 最後記得關閉工做簿 } /** * create by Mr.wang 2018/06/14 * * 生成excel流(帶表頭)。以xls爲後綴的文件,防止有些電腦不支持office07以上的 * * @param title * 標題 * @param listData * 數據內容 * @param outputStream * 輸出的流 * @param sheetName * 建立的sheet(不是文件)的名稱,若是有空,則採用sheet1做用默認的表名稱 * @param header * 表的表頭 * @throws IOException * * * example: * * List<String> title = Arrays.asList("姓名", "年齡", "生日", "郵箱"); List<List<String>> personInfos = new ArrayList<List<String>>(); List<String> person01 = Arrays.asList("Ben", "26", "1992-02-12", "ben@sina.com"); List<String> person02 = Arrays.asList("Tom", "27", "1993-08-18", "tom@sina.com"); List<String> person03 = Arrays.asList("Jack", "28", "1994-03-28", "jack@sina.com"); List<String> person04 = Arrays.asList("恩索", "29", "1995-01-09", "enso@sina.com"); personInfos.add(person01); personInfos.add(person02); personInfos.add(person03); personInfos.add(person04); File file = new File("D:/demo.xls"); FileOutputStream fos=new FileOutputStream(file); createExcelFileWithHead(title, personInfos, fos, null, "我的信息表"); ... * */ @SuppressWarnings("deprecation") public static void createExcelInStreamWithHead(List<String> title, List<List<String>> listData, OutputStream outputStream, String sheetName,String header) throws IOException { // 建立工做簿 HSSFWorkbook workBook = new HSSFWorkbook(); // 建立工做表 工做表的名字叫helloWorld if (sheetName == null || sheetName.length() == 0) { sheetName = "sheet1"; } HSSFSheet sheet = workBook.createSheet(sheetName); //設置表頭 //參數說明:1:開始行 2:結束行 3:開始列 4:結束列 //好比我要合併 第二行到第四行的 第六列到第八列 sheet.addMergedRegion(new CellRangeAddress(1,3,5,7)); sheet.addMergedRegion(new CellRangeAddress(0,0,0,title.size()-1)); HSSFRow headerRow = sheet.createRow(0); HSSFCell headerCell = headerRow.createCell(0); // 建立單元格,首先設置標題 HSSFFont font = workBook.createFont(); short fontHeightInPoints = font.getFontHeightInPoints(); font.setFontHeightInPoints((short)(fontHeightInPoints+2)); font.setBold(true); HSSFCellStyle cellHeaderStyle = workBook.createCellStyle(); cellHeaderStyle.setFont(font); cellHeaderStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); headerCell.setCellStyle(cellHeaderStyle);//可表頭加粗,居中 headerCell.setCellValue(header); //cellStyle.setAlignment(alignmentEnum);//還原,標題不居中 HSSFFont fontTitle = workBook.createFont(); fontTitle.setBold(true); HSSFCellStyle titleStyle = workBook.createCellStyle(); titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); titleStyle.setFont(fontTitle); HSSFRow titleRow = sheet.createRow(1); for (int i = 0; i < title.size(); i++) { HSSFCell titleCol = titleRow.createCell(i, CellType.STRING); titleCol.setCellValue(title.get(i)); titleCol.setCellStyle(titleStyle); } sheet.autoSizeColumn(1); // 建立數據行 HSSFCellStyle dataStyle = workBook.createCellStyle(); dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); for (int i = 0; i < listData.size(); i++) { HSSFRow dataRow = sheet.createRow(i + 2); List<String> rowData = listData.get(i); for (int j = 0; j < rowData.size(); j++) { HSSFCell dataCol = dataRow.createCell(j, CellType.STRING); dataCol.setCellValue(rowData.get(j)); dataCol.setCellStyle(dataStyle); } sheet.autoSizeColumn(i); } HSSFRow firstRow = sheet.getRow(1); int lastCellNum = firstRow.getLastCellNum(); //爲了美觀,把全部的cell擴大1/2 for(int i=0;i<lastCellNum;i++) { int columnWidth = sheet.getColumnWidth(i); sheet.setColumnWidth(i, columnWidth+columnWidth*1/2); } workBook.write(outputStream); workBook.close();// 最後記得關閉工做簿 } }
相關工具方法工具
/** * create by Mr.wang 2018/06/14 * * 將簡單的對象(讀取不到父類的屬性)轉化成List<String> * * @param o 對象 * @param convertMap 轉換器 指定對象屬性中某一個屬性值如何轉化爲String。若是不須要,能夠設置成null便可 * @param args 指定要輸出的屬性,通常用於屬性選擇和排序 ,若是不須要,則不設置.若是要查找父類的屬性,則自身及父類的屬性所有定義在此處,再也不自動搜索自身的屬性 * 這裏注意若是一樣的屬性要利用兩次,能夠使用field&alias的格式來指定轉換器 * 例如:code,code&1---->code&1能夠設定與之對應的轉換器 * @return * @throws IllegalArgumentException * @throws IllegalAccessException * @throws NoSuchFieldException * @throws SecurityException * * example: * { * "name":"jack", * "age":26, * "birthday":new Date() * } * 轉成 * ["jack","26","2018-06-14 16:02:20"] */ public static List<String> convertSimpleObj2StringList(Object o,Map<String,FieldConvert> convertMap,String... args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException{ List<String> list=new ArrayList<String>(); Class<? extends Object> objClas = o.getClass(); if(args.length==0) { Field[] declaredFields = objClas.getDeclaredFields(); for(Field f : declaredFields) { f.setAccessible(true); String fileName = f.getName(); Object obj=f.get(o);//對應的屬性沒值,則設置爲「/」 processFieldValue(convertMap, list, fileName, obj); } }else { for(String ag : args) { String fieldKey=null; String convertKey=ag; if(ag.contains("&")) { String[] split = ag.split("&"); fieldKey=split[0]; }else { fieldKey=ag; } Object fieldValue = getFieldValue(o, fieldKey); processFieldValue(convertMap, list, convertKey, fieldValue); } } return list; } private static void processFieldValue(Map<String, FieldConvert> convertMap, List<String> list, String ag, Object fieldValue) { if(fieldValue==null) { list.add("/"); return; }else { if(convertMap!=null&&convertMap.containsKey(ag)){ FieldConvert filedConvert = convertMap.get(ag); String s = filedConvert.covertFiledValueToString(fieldValue); if(s!=null){ list.add(s); }else{ list.add("/"); } }else{ list.add(fieldValue.toString()); } } } /** * create by Mr.wang 2018/06/14 * @see #convertSimpleObj2StringList * @param objs * @param convertMap * @param args * @return * @throws IllegalArgumentException * @throws IllegalAccessException * @throws NoSuchFieldException * @throws SecurityException */ public static <T> List<List<String>> convertSimpleObjList2StringList(List<T> objs,Map<String,FieldConvert> convertMap,String... args) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException{ List<List<String>> list=new ArrayList<List<String>>(); for(T obj : objs) { list.add(convertSimpleObj2StringList(obj,convertMap,args)); } return list; } /** * create by Mr.wang 2018/06/14 * 經過反射,向上(父類)一直獲取對象的屬性,若是一直獲取不到則拋 NoSuchFieldException 異常 * @param obj 要操做的操做 * @param fieldName 要獲取的屬性名稱 * @return * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalArgumentException * @throws IllegalAccessException */ public static Object getFieldValue(Object obj,String fieldName) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Class<? extends Object> class1 = obj.getClass(); Field declaredField=null; try { declaredField = class1.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { declaredField=null; } while(declaredField==null) { class1=class1.getSuperclass(); if(class1==null) { throw new NoSuchFieldException(); } try { declaredField = class1.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { declaredField=null; } } declaredField.setAccessible(true); return declaredField.get(obj); }
FieldConvert.javaspa
public interface FieldConvert { String covertFiledValueToString(Object filedValue); }