java後端匯出Excel
阿新 • • 發佈:2018-11-26
1.jxl匯出Excel的幾種方法
import jxl.CellView; import jxl.SheetSettings; import jxl.Workbook; import jxl.format.Alignment; import jxl.format.Border; import jxl.format.BorderLineStyle; import jxl.format.Colour; import jxl.format.*; import jxl.format.VerticalAlignment; import jxl.write.*; import org.apache.log4j.Logger; import java.io.File; import java.io.OutputStream; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.*; public class ExcelUtil{ private static final Logger logger = Logger.getLogger(ExcelUtil.class); //注:recordList是物件列表 /* * 匯出Excel * @param recordList:將要匯出的資料集合 物件陣列 * @param filePath:指定的路徑名 * @param out:輸出流物件 通過response.getOutputStream()傳入 * @param mapFields:匯出欄位 key:對應實體類欄位 value:對應匯出表中顯示的中文名 * @param colsSize :列寬 * @param sheetName:工作表名稱 */ public static void exportToExcel(List<Object> recordList, String filePath, OutputStream out, Map<String,String> mapFields, int[] colsSize, String sheetName){ sheetName = (sheetName != null && !sheetName.equals("")) ? sheetName : "sheet1"; WritableWorkbook wook = null; //可寫的工作簿物件 Object objClass = null; try{ if(filePath != null && !filePath.equals("")){ //檔案匯出 wook = Workbook.createWorkbook(new File(filePath)); }else{ //jsp頁面匯出 wook = Workbook.createWorkbook(out); } //設定頭部字型格式 WritableFont font = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //應用字型 WritableCellFormat wcfh = new WritableCellFormat(font); //設定其他樣式 //wcfh.setAlignment(Alignment.CENTRE); //水平對齊 wcfh.setAlignment(Alignment.LEFT); //水平對齊 wcfh.setVerticalAlignment(VerticalAlignment.CENTRE); //垂直對齊 wcfh.setBorder(Border.ALL, BorderLineStyle.THIN); //邊框 //wcfh.setBackground(Colour.AUTOMATIC); //背景色 wcfh.setWrap(true); //不自動換行 //設定內容日期格式 DateFormat df = new DateFormat("yyyy-MM-dd"); //設定內容字型格式 WritableFont font2 = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //應用日期格式 WritableCellFormat wcfc = new WritableCellFormat(font2,df); //wcfc.setAlignment(Alignment.CENTRE); wcfc.setAlignment(Alignment.LEFT); //20160420 update wcfc.setVerticalAlignment(VerticalAlignment.CENTRE); wcfc.setBorder(Border.ALL, BorderLineStyle.THIN); wcfc.setWrap(true);//自動換行 //建立工作表 WritableSheet sheet = wook.createSheet(sheetName, 0); SheetSettings setting = sheet.getSettings(); setting.setVerticalFreeze(1); //凍結視窗頭部 Integer colsNum = mapFields.size(); //設定列寬 if (colsSize.length == colsNum) { for (int i = 0; i < colsSize.length; i++) { sheet.setColumnView(i, colsSize[i]); } } else { // 設定預設的寬度 for (int i = 0; i < colsNum; i++) { CellView cellView = new CellView(); cellView.setAutosize(true); //設定自動大小 sheet.setColumnView(i, cellView);//根據內容自動設定列寬 } } int columnIndex = 0; //列索引 List<String> methodNameList = new ArrayList<String>(); if(mapFields != null){ String key = ""; Map<String, Method> getMap = null; Method method = null; //開始匯出表格頭部 for(Iterator<String> i = mapFields.keySet().iterator(); i.hasNext();){ key = i.next(); //應用wcfh樣式建立單元格 sheet.addCell(new Label(columnIndex, 0, mapFields.get(key),wcfh)); methodNameList.add(key); columnIndex++; } if(recordList != null && recordList.size() > 0){ //匯出表格內容 for(int i = 0, len = recordList.size(); i<len ; i++){ objClass = recordList.get(i); getMap = getAllMethod(objClass); //獲得物件所有的get方法 //按儲存的欄位順序匯出內容 for(int j = 0; j < methodNameList.size(); j++){ //根據key獲取對應方法 method = getMap.get("GET" + methodNameList.get(j).toString().toUpperCase()); if(method != null){ //從對應的get方法得到返回值 //System.out.println("method: " + method); String value = ""; //20160304 update if(method.getGenericReturnType().toString().equals("class java.util.Date")){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(method.invoke(objClass, (Object[])null) == null){ value = ""; }else{ value = formatter.format(method.invoke(objClass, (Object[])null)); } }else if(method.getGenericReturnType().toString().equals("class java.sql.Date")){ //20160421 update SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if(method.invoke(objClass, (Object[])null) == null){ value = ""; }else{ value = formatter.format(method.invoke(objClass, (Object[])null)); } } else{ if(method.invoke(objClass, (Object[])null) == null){ value = ""; }else{ value = method.invoke(objClass, (Object[])null).toString(); } } //應用wcfc樣式建立單元格 sheet.addCell(new Label(j, i+1, value, wcfc)); }else{ sheet.addCell(new Label(j, i+1, "", wcfc)); } } //內容匯出裡層for迴圈結束 } //內容匯出外層for迴圈結束 } //recordList不為空 wook.write(); System.out.println("匯出Excel成功"); }/*else{ //欄位引數為null throw new Exception("傳入引數不合法"); }*/ }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(wook != null){ wook.close(); } if(out != null){ out.flush(); out.close(); } }catch(Exception e2){ e2.printStackTrace(); } } //finally結束 } /** * 獲取類的所有get方法 * @param obj * @return 類中所有的get方法 */ public static HashMap<String, Method> getAllMethod(Object obj) throws Exception{ HashMap<String, Method> map = new HashMap<String, Method>(); Method[] methods = obj.getClass().getMethods(); String methodName = ""; for(int i = 0; i < methods.length; i++){ methodName = methods[i].getName().toUpperCase(); if(methodName.startsWith("GET")){ map.put(methodName, methods[i]); } } return map; } /**將物件列表轉化為二維資料列表 * @param recordList 物件列表 * @param methodNameList 需要放入資料列表中的欄位名 * */ public static List<Object> convertObjectListToDataList(List recordList,List<String> methodNameList) throws Exception { List<Object> dataList = new ArrayList<Object>(); Map<String, Method> getMap = null; Method method = null; if (recordList != null && recordList.size() > 0) { //匯出表格內容 for (int i = 0, len = recordList.size(); i < len; i++) { List<Object> tempList = new ArrayList<Object>(); Object temp = recordList.get(i); getMap = getAllMethod(temp); //獲得物件所有的get方法 //按儲存的欄位順序匯出內容 for (int j = 0; j < methodNameList.size(); j++) { //根據key獲取對應方法 method = getMap.get("GET" + methodNameList.get(j).toString().toUpperCase()); if (method != null) { //從對應的get方法得到返回值 //System.out.println("method: " + method); String value = ""; //20160304 update if (method.getGenericReturnType().toString().equals("class java.util.Date")) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if (method.invoke(temp, (Object[]) null) == null) { value = ""; } else { value = formatter.format(method.invoke(temp, (Object[]) null)); } } else if (method.getGenericReturnType().toString().equals("class java.sql.Date")) { //20160421 update SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if (method.invoke(temp, (Object[]) null) == null) { value = ""; } else { value = formatter.format(method.invoke(temp, (Object[]) null)); } } else if (method.getGenericReturnType().toString().equals("class java.sql.Timestamp")) { //20160421 update SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); if (method.invoke(temp, (Object[]) null) == null) { value = ""; } else { value = formatter.format(method.invoke(temp, (Object[]) null)); } } else { if (method.invoke(temp, (Object[]) null) == null) { value = ""; } else { value = method.invoke(temp, (Object[]) null).toString(); } } //應用wcfc樣式建立單元格 if(value.equals("")){ tempList.add("\\"); }else{ tempList.add(value); } } else { tempList.add("\\"); } } //內容匯出裡層for迴圈結束 dataList.add(tempList); } //內容匯出外層for迴圈結束 } //recordList不為空 return dataList; } /*public static void main(String[] args) throws Exception{ SendTaskInnerQuery obj = new SendTaskInnerQuery(); getAllMethod(obj); }*/ /** * 根據指定路徑匯出Excel * @param list * @param filePath * @param mapFields * @param sheetName */ public static void ImportExcel(List list,String filePath,Map<String, String> mapFields,int[] colsSize,String sheetName){ exportToExcel(list,filePath,null,mapFields,colsSize,sheetName); } /** * 從Jsp頁面匯出Excel * @param list * @param out * @param mapFields * @param colsSize * @param sheetName */ public static void ImportExcel(List list,OutputStream out,Map<String, String> mapFields,int[] colsSize, String sheetName){ exportToExcel(list,null,out,mapFields,colsSize,sheetName); } //注:recordList是列表的列表,相當於一個二維陣列 /** * 匯出Excel * @param recordList:將要匯出的資料集合 二維陣列 * @param filePath:指定的路徑名 * @param out:輸出流物件 通過response.getOutputStream()傳入 * @param mapFields:匯出欄位 key:對應實體類欄位 value:對應匯出表中顯示的中文名 * @param colsSize :列寬 * @param sheetName:工作表名稱 */ public static void exportToExcel2(List<Object> recordList, String filePath, OutputStream out, Map<String,String> mapFields, int[] colsSize, String sheetName){ sheetName = (sheetName != null && !sheetName.equals("")) ? sheetName : "sheet1"; WritableWorkbook wook = null; //可寫的工作簿物件 List<Object> objClass = null; try{ if(filePath != null && !filePath.equals("")){ //檔案匯出 wook = Workbook.createWorkbook(new File(filePath)); }else{ //jsp頁面匯出 wook = Workbook.createWorkbook(out); } //設定頭部字型格式 WritableFont font = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //應用字型 WritableCellFormat wcfh = new WritableCellFormat(font); //設定其他樣式 wcfh.setAlignment(Alignment.CENTRE); //水平對齊 wcfh.setVerticalAlignment(VerticalAlignment.CENTRE); //垂直對齊 wcfh.setBorder(Border.ALL, BorderLineStyle.THIN); //邊框 //wcfh.setBackground(Colour.AUTOMATIC); //背景色 wcfh.setWrap(true); //不自動換行 //設定內容日期格式 DateFormat df = new DateFormat("yyyy-MM-dd"); //設定內容字型格式 WritableFont font2 = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //應用日期格式 WritableCellFormat wcfc = new WritableCellFormat(font2,df); wcfc.setAlignment(Alignment.LEFT); wcfc.setVerticalAlignment(VerticalAlignment.CENTRE); wcfc.setBorder(Border.ALL, BorderLineStyle.THIN); wcfc.setWrap(true);//自動換行 //建立工作表 WritableSheet sheet = wook.createSheet(sheetName, 0); SheetSettings setting = sheet.getSettings(); setting.setVerticalFreeze(1); //凍結視窗頭部 Integer colsNum = mapFields.size(); //設定列寬 if (colsSize.length == colsNum) { for (int i = 0; i < colsSize.length; i++) { sheet.setColumnView(i, colsSize[i]); } } else { // 設定預設的寬度 for (int i = 0; i < colsNum; i++) { CellView cellView = new CellView(); cellView.setAutosize(true); //設定自動大小 sheet.setColumnView(i, cellView);//根據內容自動設定列寬 } } int columnIndex = 0; //列索引 List<String> methodNameList = new ArrayList<String>(); if(mapFields != null){ String key = ""; Map<String, Method> getMap = null; Method method = null; //開始匯出表格頭部 for(Iterator<String> i = mapFields.keySet().iterator(); i.hasNext();){ key = i.next(); //應用wcfh樣式建立單元格 sheet.addCell(new Label(columnIndex, 0, mapFields.get(key),wcfh)); methodNameList.add(key); columnIndex++; } if(recordList != null && recordList.size() > 0){ //匯出表格內容 System.out.println("recordList.size():" + recordList.size()); System.out.println("recordList.get(0).size():" + ((List)recordList.get(0)).size()); for(int i = 0, len = recordList.size(); i<len ; i++){ objClass =(List) recordList.get(i); //System.out.println("objClass.size():" + objClass.size()); //按儲存的欄位順序匯出內容 for(int j = 0; j < objClass.size(); j++){ //根據key獲取對應方法 //String value = (String)objClass.get(j); String value = String.valueOf(objClass.get(j)); //應用wcfc樣式建立單元格 sheet.addCell(new Label(j, i+1, value, wcfc)); } //內容匯出裡層for迴圈結束 } //內容匯出外層for迴圈結束 } //recordList不為空 wook.write(); System.out.println("匯出Excel成功"); }/*else{ //欄位引數為null throw new Exception("傳入引數不合法"); }*/ }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(wook != null){ wook.close(); } if(out != null){ out.flush(); out.close(); } }catch(Exception e2){ e2.printStackTrace(); } } //finally結束 } /** * 根據指定路徑匯出Excel * @param list * @param filePath * @param mapFields * @param sheetName */ public static void ImportExcel2(List list,String filePath,Map<String, String> mapFields,int[] colsSize,String sheetName){ exportToExcel2(list,filePath,null,mapFields,colsSize,sheetName); } /** * 從Jsp頁面匯出Excel * @param list * @param out * @param mapFields * @param sheetName */ public static void ImportExcel2(List list,OutputStream out,Map<String, String> mapFields,int[] colsSize,String sheetName){ exportToExcel2(list,null,out,mapFields,colsSize,sheetName); } //注:recordList是列表的列表,相當於一個二維陣列; 標題行可以是多行 /** * 匯出Excel * @param recordList:將要匯出的資料集合 二維陣列 * @param filePath:指定的路徑名 * @param out:輸出流物件 通過response.getOutputStream()傳入 * @param mapFields:二維陣列 一維的大小是標題行的行數 二維的大小是標題行的列數 * @param colsSize :列寬 * @param sheetName:工作表名稱 * @param mergePosList 二維陣列 每個一維包含 合併單元格的列表座標 起始列 起始行 結束列 結束行 */ public static void exportToExcel3(List<Object> recordList, String filePath, OutputStream out, List<Object> mapFields, int[] colsSize, String sheetName, List<Object> mergePosList){ logger.info("filePath: " + filePath); sheetName = (sheetName != null && !sheetName.equals("")) ? sheetName : "sheet1"; WritableWorkbook wook = null; //可寫的工作簿物件 List<Object> objClass = null; int titleRowNum = 0; if(mapFields != null){ titleRowNum = mapFields.size(); } try{ if(filePath != null && !filePath.equals("")){ //檔案匯出 wook = Workbook.createWorkbook(new File(filePath)); }else{ //jsp頁面匯出 wook = Workbook.createWorkbook(out); } //設定頭部字型格式 WritableFont font = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //應用字型 WritableCellFormat wcfh = new WritableCellFormat(font); //設定其他樣式 wcfh.setAlignment(Alignment.CENTRE); //水平對齊 wcfh.setVerticalAlignment(VerticalAlignment.CENTRE); //垂直對齊 wcfh.setBorder(Border.ALL, BorderLineStyle.THIN); //邊框 //wcfh.setBackground(Colour.AUTOMATIC); //背景色 wcfh.setWrap(true); //自動換行 //設定內容日期格式 DateFormat df = new DateFormat("yyyy-MM-dd"); //應用日期格式 //設定內容字型格式 WritableFont font2 = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); WritableCellFormat wcfc = new WritableCellFormat(font2,df); wcfc.setAlignment(Alignment.LEFT); wcfc.setVerticalAlignment(VerticalAlignment.CENTRE); wcfc.setBorder(Border.ALL, BorderLineStyle.THIN); wcfc.setWrap(true); //建立工作表 WritableSheet sheet = wook.createSheet(sheetName, 0); SheetSettings setting = sheet.getSettings(); setting.setVerticalFreeze(2); //凍結視窗頭部 Integer colsNum = 0; if(mapFields != null && mapFields.size() != 0){ colsNum = ((List)mapFields.get(0)).size(); } logger.info("export excel 3 colsNum: " + colsNum); //設定列寬 if (colsSize.length == colsNum) { for (int i = 0; i < colsSize.length; i++) { sheet.setColumnView(i, colsSize[i]); } } else { // 設定預設的寬度 for (int i = 0; i < colsNum; i++) { CellView cellView = new CellView(); cellView.setAutosize(true); //設定自動大小 sheet.setColumnView(i, cellView);//根據內容自動設定列寬 } } //20170905 add 設定行高 if(recordList != null && recordList.size() > 0){ //標題行 sheet.setRowView(0, 500,false); for (int i = 0; i < recordList.size(); i++) { sheet.setRowView(i+1, 500,false); } } //向Excel中寫標題行 if(mapFields != null){ //開始匯出表格頭部 for(int i = 0; i<mapFields.size(); i++){//標題行 List<Object> tempList = (List<Object>)mapFields.get(i); for(int j=0; j<tempList.size(); j++){//標題列 //應用wcfh樣式建立單元格 sheet.addCell(new Label(j, i, String.valueOf(tempList.get(j)),wcfh)); } } //合併標題行單元格 logger.info("mergePosList.size(): " + mergePosList.size()); for(int i=0; i<mergePosList.size(); i++){ List<Object> tempPosList = (List<Object>)mergePosList.get(i); sheet.mergeCells((Integer)tempPosList.get(0), (Integer)tempPosList.get(1), (Integer)tempPosList.get(2), (Integer)tempPosList.get(3)); logger.info("i: " + i + "-- " + (Integer)tempPosList.get(0)+ ","+(Integer)tempPosList.get(1) +"," + (Integer)tempPosList.get(2) + "," + (Integer)tempPosList.get(3)); } //向Excel中寫內容行 if(recordList != null && recordList.size() > 0){ //匯出表格內容 System.out.println("recordList.size():" + recordList.size()); System.out.println("recordList.get(0).size():" + ((List)recordList.get(0)).size()); for(int i = 0, len = recordList.size(); i<len ; i++){ objClass =(List) recordList.get(i); //System.out.println("objClass.size():" + objClass.size()); //按儲存的欄位順序匯出內容 for(int j = 0; j < objClass.size(); j++){ //根據key獲取對應方法 //String value = (String)objClass.get(j); String value = String.valueOf(objClass.get(j)); //應用wcfc樣式建立單元格 sheet.addCell(new Label(j, i+titleRowNum, value, wcfc)); } //內容匯出裡層for迴圈結束 } //內容匯出外層for迴圈結束 } //recordList不為空 wook.write(); System.out.println("匯出Excel成功"); }else{ //欄位引數為null throw new Exception("傳入引數不合法"); } }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(wook != null){ wook.close(); } if(out != null){ out.flush(); out.close(); } }catch(Exception e2){ e2.printStackTrace(); } } //finally結束 } /** * 根據指定路徑匯出Excel * @param list * @param filePath * @param mapFields * @param sheetName */ public static void ImportExcel3(List list,String filePath, List<Object> mapFields,int[] colsSize,String sheetName,List<Object> mergePosList){ exportToExcel3(list,filePath,null,mapFields,colsSize,sheetName,mergePosList); } /** * 從Jsp頁面匯出Excel * @param list * @param out * @param mapFields * @param sheetName */ public static void ImportExcel3(List list,OutputStream out, List<Object> mapFields,int[] colsSize,String sheetName,List<Object> mergePosList){ exportToExcel3(list,null,out,mapFields,colsSize,sheetName,mergePosList); } /** * @param wook 工作簿 * @param index sheet索引 * */ //20160214 新增可以匯出多個sheet的excel方法 public static void exportToExcelSheet(List<Object> recordList, String filePath, OutputStream out, Map<String,String> mapFields, int[] colsSize, String sheetName,WritableWorkbook wook,int index) throws Exception{ sheetName = (sheetName != null && !sheetName.equals("")) ? sheetName : "sheet1"; Object objClass = null; //設定頭部字型格式 WritableFont font = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //應用字型 WritableCellFormat wcfh = new WritableCellFormat(font); //設定其他樣式 wcfh.setAlignment(Alignment.CENTRE); //水平對齊 wcfh.setVerticalAlignment(VerticalAlignment.CENTRE); //垂直對齊 wcfh.setBorder(Border.ALL, BorderLineStyle.THIN); //邊框 //wcfh.setBackground(Colour.AUTOMATIC); //背景色 wcfh.setWrap(true); //不自動換行 //設定內容日期格式 DateFormat df = new DateFormat("yyyy-MM-dd"); //設定內容字型格式 WritableFont font2 = new WritableFont(WritableFont.TIMES, 10, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK); //應用日期格式 WritableCellFormat wcfc = new WritableCellFormat(font2,df); wcfc.setAlignment(Alignment.LEFT); wcfc.setVerticalAlignment(VerticalAlignment.CENTRE); wcfc.setBorder(Border.ALL, BorderLineStyle.THIN); wcfc.setWrap(true);//自動換行 //建立工作表 WritableSheet sheet = wook.createSheet(sheetName, index);//index是sheet的索引 SheetSettings setting = sheet.getSettings(); setting.setVerticalFreeze(1); //凍結視窗頭部 Integer colsNum = mapFields.size(); //設定列寬 if (colsSize.length == colsNum) { for (int i = 0; i < colsSize.length; i++) { sheet.setColumnView(i, colsSize[i]); } } else { // 設定預設的寬度 for (int i = 0; i < colsNum; i++) { CellView cellView = new CellView(); cellView.setAutosize(true); //設定自動大小 sheet.setColumnView(i, cellView);//根據內容自動設定列寬 } } int columnIndex = 0; //列索引 List<String> methodNameList = new ArrayList<String>(); if(mapFields != null){ String key = ""; Map<String, Method> getMap = null; Method method = null; //開始匯出表格頭部 for(Iterator<String> i = mapFields.keySet().iterator(); i.hasNext();){ key = i.next(); //應用wcfh樣式建立單元格 sheet.addCell(new Label(columnIndex, 0, mapFields.get(key),wcfh)); methodNameList.add(key); columnIndex++; } if(recordList != null && recordList.size() > 0){ //匯出表格內容 for(int i = 0, len = recordList.size(); i<len ; i++){ objClass = recordList.get(i); getMap = getAllMethod(objClass); //獲得物件所有的get方法 //按儲存的欄位順序匯出內容 for(int j = 0; j < methodNameList.size(); j++){ //根據key獲取對應方法 method = getMap.get("GET" + methodNameList.get(j).toString().toUpperCase()); if(method != null){ //從對應的get方法得到返回值 //System.out.println("method: " + method); String value = ""; if(method.invoke(objClass, (Object[])null) != null){ //20160304 update if(method.getGenericReturnType().toString().equals("class java.util.Date")){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); if(method.invoke(objClass, (Object[])null) == null){ value = ""; }else{ value = formatter.format(method.invoke(objClass, (Object[])null)); } }else{ if(method.invoke(objClass, (Object[])null) == null){ value = ""; }else{ value = method.invoke(objClass, (Object[])null).toString(); } } } //應用wcfc樣式建立單元格 sheet.addCell(new Label(j, i+1, value, wcfc)); }else{ sheet.addCell(new Label(j, i+1, "", wcfc)); } } //內容匯出裡層for迴圈結束 } //內容匯出外層for迴圈結束 } //recordList不為空 }/*else{ //欄位引數為null throw new Exception("傳入引數不合法"); }*/ } private static void exportToExcel4(List<Object> dataList, String filePath, OutputStream out, List<Map<String, String>> mapFieldList, List<int[]> colsSizeList, List<String> sheetNameList) { // TODO Auto-generated method stub WritableWorkbook wook = null; try{ wook = Workbook.createWorkbook(out); //可寫的工作簿物件 for(int i=0; i<sheetNameList.size(); i++){ List<Object> recordList = (List<Object>)dataList.get(i); Map<String,String> mapFileds = mapFieldList.get(i); int[] colsSize = colsSizeList.get(i); String sheetName = sheetNameList.get(i); logger.info("i - " + i + " : sheetName - " + sheetName); exportToExcelSheet(recordList,null,out,mapFileds,colsSize,sheetName,wook,i); } wook.write(); System.out.println("匯出Excel成功"); }catch(Exception e){ e.printStackTrace(); }finally{ try{ if(wook != null){ wook.close(); } if(out != null){ out.flush(); out.close(); } }catch(Exception e2){ e2.printStackTrace(); } } //finally結束 } public static void ImportExcel4(List<Object> dataList, OutputStream out, List<Map<String, String>> mapFieldList, List<int[]> colsSizeList, List<String> sheetNameList) { // TODO Auto-generated method stub exportToExcel4(dataList,null,out,mapFieldList,colsSizeList,sheetNameList); } }
2.呼叫形式
//1.標題 Map<String, String> mapField = new LinkedHashMap<String, String>(); mapField.put("num", "序號");//0 //2.設定列寬 Integer fieldNum = mapField.keySet().size(); int[] colsSize = new int[fieldNum]; for(int i=0; i<fieldNum; i++){ if(i==0 || i==1 || i==2 || i==3){ colsSize[i] = 8; }else if(i==7){ //需求名稱 colsSize[i] = 16; }else if(i==8 || i==15){ //需求描述 驗證方案 colsSize[i] = 30; }else{ colsSize[i] = 12; } } //3.標題行 List<Object> titleList = new ArrayList<Object>(); //第一行 List<Object> tempList1 = new ArrayList<Object>(); tempList1.add("序號"); // 1 //第二行 List<Object> tempList2 = new ArrayList<Object>(); tempList2.add("序號"); // 1 titleList.add(tempList1); titleList.add(tempList2); //4.設定合併單元格的列表座標 起始列 起始行 結束列 結束行 List<Object> mergePosList = new ArrayList<Object>(); List<Object> tempPosList1 = new ArrayList<Object>(); tempPosList1.add(18); tempPosList1.add(0); tempPosList1.add(23); tempPosList1.add(0); List<Object> tempPosList2 = new ArrayList<Object>(); tempPosList2.add(24); tempPosList2.add(0); tempPosList2.add(29); tempPosList2.add(0); mergePosList.add(tempPosList1); mergePosList.add(tempPosList2); //5.將查詢物件列表轉化為匯出需要的形式 List<Object> dataList = ExcelUtil.convertObjectListToDataList(resultList,keyList); response.reset(); response.setContentType("application/msexcel"); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String nowTime = sdf.format(new Date()); String fileName = nowTime + "_匯出列表"; response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),"iso8859-1") + ".xls"); ExcelUtil.ImportExcel3(dataList,response.getOutputStream(), titleList, colsSize, fileName, mergePosList);