java poi excel 生成表格的工具封装
生活随笔
收集整理的這篇文章主要介紹了
java poi excel 生成表格的工具封装
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
效果如下:
代碼如下:
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();// 創建工作表 工作表的名字叫helloWorldif (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/2for(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();// 創建工作表 工作表的名字叫helloWorldif (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/2for(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.java
public interface FieldConvert {String covertFiledValueToString(Object filedValue); }?
轉載于:https://www.cnblogs.com/wangyang108/p/9182714.html
總結
以上是生活随笔為你收集整理的java poi excel 生成表格的工具封装的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: oracle 数据库新建实例导入数据
- 下一篇: 宏杉科技中标中国移动存储集采喜获50%份