Java使用POI匯出Excel工具類
阿新 • • 發佈:2019-01-01
自行匯入poi3.9的jar包
工具類:
package com.cpic.caf.template.home.util; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFComment; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFPatriarch; 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.apache.poi.hssf.util.HSSFColor; /** * * @author librag * @version v1.0 * @param <T> * 應用泛型,代表任意一個符合javabean風格的類 * 注意這裡為了簡單起見,boolean型的屬性xxx的get器方式為getXxx(),而不是isXxx() * byte[]表jpg格式的圖片資料 */ public class ExportExcel<T>{ public static final String Map = "Map"; public static final String List = "List"; private int List_Size = 0; /* public ExportExcel(int List_Size) { this.List_Size = List_Size; } public ExportExcel() { }*/ /** * @param title * 表格標題名 * @param headers * 表格屬性列名陣列 * @param dataset 允許的型別(實體類,List<List<Object>>,List<Map<String,Object>>) * 需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 * javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料) * @param out * 與輸出裝置關聯的流物件,可以將EXCEL文件匯出到本地檔案或者網路中 * @param pattern * 如果有時間資料,設定輸出格式。預設為"yyy-MM-dd" Controller示例 //引用瀏覽器引擎下載 //使用本工具類建立物件 ExportExcel<物件> ex = new ExportExcel<物件>(); //建立列 String[] headers = { "主鍵", "從業者ID", "案例是作品集還是婚禮案例", "案例型別", "標題","案例地址","描述","置頂","刪除狀態","訪問量","收藏量"}; //建立值列 List<物件> dataset = Service.方法名(); //呼叫工具類物件 ex.exportExcel(headers,dataset,response); //提示 System.out.println("excel匯出成功!"); Controller示例2 //直接下載到本地磁碟 //使用本工具類建立物件 ExportExcel<Map<String, Object>> ex = new ExportExcel<物件>(); //建立列 String[] headers = { "主鍵", "從業者ID", "案例是作品集還是婚禮案例", "案例型別", "標題","案例地址","描述","置頂","刪除狀態","訪問量","收藏量"}; //建立值列 List<Map<String, Object>> dataset = Service.方法名(); //呼叫工具類物件 ex.exportExcel(headers,dataset,"E:\\資料夾名\\資料夾名"); //提示 System.out.println("excel匯出成功!"); */ /** * 方法過載同時指向一個unchecked * @param dataset Value列 * @param response 必須 * @param path (當傳入指定path時 方法會使用IO流下載到指定地址(資料夾) || 反之 會引用瀏覽器的下載引擎) */ public void exportExcel(Collection<T> dataset,String path){ exportExcel("EXCEL文件", null, dataset, "yyyy-MM-dd",path); } public void exportExcel(String[] headers, Collection<T> dataset,String path) { exportExcel("EXCEL文件", headers, dataset, "yyyy-MM-dd",path); } public void exportExcel(String[] headers, Collection<T> dataset, String pattern,String path){ exportExcel("EXCEL文件", headers, dataset, pattern,path); } public void exportExcel(Collection<T> dataset,HttpServletResponse response){ exportExcel("EXCEL文件", null, dataset, "yyyy-MM-dd",response); } public void exportExcel(String[] headers, Collection<T> dataset,HttpServletResponse response) { exportExcel("EXCEL文件", headers, dataset, "yyyy-MM-dd",response); } public void exportExcel(String[] headers, Collection<T> dataset, String pattern,HttpServletResponse response){ exportExcel("EXCEL文件", headers, dataset, pattern,response); } public void exportExcel(String[] headers, List<List<Object>> dataset,HttpServletResponse response) { exportExcel("EXCEL文件", headers, dataset, "yyyy-MM-dd",response); } public void MapExportExcel(String[] headers, List<Map<String, Object>> dataset,HttpServletResponse response) { exportExcel("EXCEL文件", headers, dataset, "yyyy-MM-dd",response,"Map"); } /** * 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的資料以EXCEL 的形式輸出到指定IO裝置上 * * @param title 表格標題名 * @param headers 表格屬性列名陣列 * @param dataset 需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 * javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料) * @param pattern 如果有時間資料,設定輸出格式。預設為"yyy-MM-dd" */ @SuppressWarnings("unchecked") public void exportExcel(String title, String[] headers,Collection<T> dataset, String pattern,String path){ // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(title); // 設定表格預設列寬度為15個位元組 sheet.setDefaultColumnWidth((short) 15); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設定這些樣式 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); // 生成並設定另一個樣式 HSSFCellStyle style2 = workbook.createCellStyle(); 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); // 宣告一個畫圖的頂級管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定義註釋的大小和位置,詳見文件 HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // 設定註釋內容 comment.setString(new HSSFRichTextString("可以在POI中添加註釋!")); // 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容. comment.setAuthor("leno"); // 產生表格標題行 HSSFRow row = sheet.createRow(0); for (short i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } try { // 遍歷集合資料,產生資料行 Iterator<T> it = dataset.iterator(); int index = 0; while (it.hasNext()) { index++; row = sheet.createRow(index); T t = (T) it.next(); // 利用反射,根據javabean屬性的先後順序,動態呼叫getXxx()方法得到屬性值 Field[] fields = t.getClass().getDeclaredFields(); for (short i = 0; i < fields.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style2); Field field = fields[i]; String fieldName = field.getName(); String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Class tCls = t.getClass(); Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); // 判斷值的型別後進行強制型別轉換 String textValue = null; /* if (value instanceof Integer) { int intValue = (Integer) value; cell.setCellValue(intValue); } else if (value instanceof Float) { float fValue = (Float) value; textValue = new HSSFRichTextString( String.valueOf(fValue)); cell.setCellValue(textValue); } else if (value instanceof Double) { double dValue = (Double) value; textValue = new HSSFRichTextString( String.valueOf(dValue)); cell.setCellValue(textValue); } else if (value instanceof Long) { long longValue = (Long) value; cell.setCellValue(longValue); }*/ if (value instanceof Boolean) { boolean bValue = (Boolean) value; textValue = "男"; if (!bValue) { textValue = "女"; } } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); } else if (value instanceof byte[]) { // 有圖片時,設定行高為60px; row.setHeightInPoints(60); // 設定圖片所在列寬度為80px,注意這裡單位的一個換算 sheet.setColumnWidth(i, (short) (35.7 * 80)); // sheet.autoSizeColumn(i); byte[] bsValue = (byte[]) value; HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index); anchor.setAnchorType(2); patriarch.createPicture(anchor, workbook.addPicture( bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); } else { // 其它資料型別都當作字串簡單處理 textValue = value.toString(); } // 如果不是圖片資料,就利用正則表示式判斷textValue是否全部由數字組成 if (textValue != null) { Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { HSSFRichTextString richString = new HSSFRichTextString( textValue); HSSFFont font3 = workbook.createFont(); font3.setColor(HSSFColor.BLUE.index); richString.applyFont(font3); cell.setCellValue(richString); } } } } }catch (SecurityException e){ e.printStackTrace(); }catch (NoSuchMethodException e){ e.printStackTrace(); }catch (IllegalArgumentException e){ e.printStackTrace(); }catch (IllegalAccessException e){ e.printStackTrace(); }catch (InvocationTargetException e){ e.printStackTrace(); }finally{ // 清理資源 } //生成檔案流 IOExcle(workbook,path); } /** * (網路傳輸) * 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的資料以EXCEL 的形式輸出到指定IO裝置上 * @param title 表格標題名 * @param headers 表格屬性列名陣列 * @param dataset 需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 * javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料) * @param pattern 如果有時間資料,設定輸出格式。預設為"yyy-MM-dd" */ @SuppressWarnings("unchecked") public void exportExcel(String title, String[] headers,Collection<T> dataset, String pattern,HttpServletResponse response){ response.reset(); // 清除buffer快取 // 指定下載的檔名 response.setHeader("Content-Disposition", "attachment;filename=contacts" + getDateTimeName() + ".xls"); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(title); // 設定表格預設列寬度為15個位元組 sheet.setDefaultColumnWidth((short) 15); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設定這些樣式 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); // 生成並設定另一個樣式 HSSFCellStyle style2 = workbook.createCellStyle(); 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); // 宣告一個畫圖的頂級管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定義註釋的大小和位置,詳見文件 HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // 設定註釋內容 comment.setString(new HSSFRichTextString("可以在POI中添加註釋!")); // 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容. comment.setAuthor("leno"); // 產生表格標題行 HSSFRow row = sheet.createRow(0); for (short i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } try { // 遍歷集合資料,產生資料行 Iterator<T> it = dataset.iterator(); int index = 0; while (it.hasNext()){ index++; row = sheet.createRow(index); T t = (T) it.next(); // 利用反射,根據javabean屬性的先後順序,動態呼叫getXxx()方法得到屬性值 Field[] fields = t.getClass().getDeclaredFields(); for (short i = 0; i < fields.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style2); Field field = fields[i]; String fieldName = field.getName(); String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Class tCls = t.getClass(); Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); Object value = getMethod.invoke(t, new Object[] {}); // 判斷值的型別後進行強制型別轉換 String textValue = null; if (value instanceof Boolean) { boolean bValue = (Boolean) value; textValue = "男"; if (!bValue) { textValue = "女"; } } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); } else if (value instanceof byte[]) { // 有圖片時,設定行高為60px; row.setHeightInPoints(60); // 設定圖片所在列寬度為80px,注意這裡單位的一個換算 sheet.setColumnWidth(i, (short) (35.7 * 80)); // sheet.autoSizeColumn(i); byte[] bsValue = (byte[]) value; HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, index, (short) 6, index); anchor.setAnchorType(2); patriarch.createPicture(anchor, workbook.addPicture( bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); } else { // 其它資料型別都當作字串簡單處理 textValue = value.toString(); } // 如果不是圖片資料,就利用正則表示式判斷textValue是否全部由數字組成 if (textValue != null) { Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { HSSFRichTextString richString = new HSSFRichTextString( textValue); HSSFFont font3 = workbook.createFont(); font3.setColor(HSSFColor.BLUE.index); richString.applyFont(font3); cell.setCellValue(richString); } } } }//while }catch (SecurityException e){ e.printStackTrace(); }catch (NoSuchMethodException e){ e.printStackTrace(); }catch(IllegalArgumentException e) { e.printStackTrace(); }catch (IllegalAccessException e){ e.printStackTrace(); }catch (InvocationTargetException e){ e.printStackTrace(); }finally{ // 清理資源 } //生成檔案流 HTTPExcle(workbook,response); } /** * (網路傳輸)集合 * 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的資料以EXCEL 的形式輸出到指定IO裝置上 * @param title 表格標題名 * @param headers 表格屬性列名陣列 * @param dataset 需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 * javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料) * @param pattern 如果有時間資料,設定輸出格式。預設為"yyy-MM-dd" */ @SuppressWarnings("unchecked") public void exportExcel(String title, String[] headers,List<List<Object>> dataset, String pattern,HttpServletResponse response){ response.reset(); // 清除buffer快取 // 指定下載的檔名 response.setHeader("Content-Disposition", "attachment;filename=contacts" + getDateTimeName() + ".xls"); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(title); // 設定表格預設列寬度為15個位元組 sheet.setDefaultColumnWidth((short) 15); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設定這些樣式 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); // 生成並設定另一個樣式 HSSFCellStyle style2 = workbook.createCellStyle(); 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); // 宣告一個畫圖的頂級管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定義註釋的大小和位置,詳見文件 HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // 設定註釋內容 comment.setString(new HSSFRichTextString("可以在POI中添加註釋!")); // 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容. comment.setAuthor("leno"); // 產生表格標題行 HSSFRow row = sheet.createRow(0); for (short i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } try { for (int i = 0; i < dataset.size(); i++) { //建立外層集合行 HSSFRow createRow = sheet.createRow(i+1); for (int j = 0; j < dataset.get(i).size(); j++) { createRow.createCell(j).setCellValue(dataset.get(i).get(j).toString());; } } }catch (Exception e){ e.printStackTrace(); }finally{ // 清理資源 } //生成檔案流 HTTPExcle(workbook,response); } /** * (網路傳輸)集合Map * 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的資料以EXCEL 的形式輸出到指定IO裝置上 * @param title 表格標題名 * @param headers 表格屬性列名陣列 * @param dataset 需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 * javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料) * @param pattern 如果有時間資料,設定輸出格式。預設為"yyy-MM-dd" */ @SuppressWarnings("unchecked") public void exportExcel(String title, String[] headers,List<Map<String, Object>> dataset, String pattern,HttpServletResponse response,String name){ response.reset(); // 清除buffer快取 // 指定下載的檔名 response.setHeader("Content-Disposition", "attachment;filename=contacts" + getDateTimeName() + ".xls"); response.setContentType("application/vnd.ms-excel;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(title); // 設定表格預設列寬度為15個位元組 sheet.setDefaultColumnWidth((short) 15); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設定這些樣式 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); // 生成並設定另一個樣式 HSSFCellStyle style2 = workbook.createCellStyle(); 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); // 宣告一個畫圖的頂級管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定義註釋的大小和位置,詳見文件 HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // 設定註釋內容 comment.setString(new HSSFRichTextString("可以在POI中添加註釋!")); // 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容. comment.setAuthor("leno"); // 產生表格標題行 HSSFRow row = sheet.createRow(0); for (short i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } try { dataset = nullToEmpty(dataset); for (int i = 0; i < dataset.size(); i++) { //建立外層集合行 HSSFRow createRow = sheet.createRow((i+1)); //第一種 Set<String> set = dataset.get(i).keySet(); //取出所有的key值 Iterator<String> it = set.iterator(); int j = 0; while(it.hasNext()) { /* String str = null; if(it.next()!=null&&dataset.get(i)!=null&&dataset.get(i).get(it.next())!=null) { System.out.println("----------------------------"); System.out.println(it.next()); System.out.println(dataset.get(i).get(it.next())); str = dataset.get(i).get(it.next()).toString(); }*/ Object value = dataset.get(i).get(it.next()); String textValue = null; if (value instanceof Boolean){ boolean bValue = (Boolean) value; textValue = "男"; if (!bValue) { textValue = "女"; } }else if (value instanceof Date){ Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat(pattern); textValue = sdf.format(date); }else if (value instanceof byte[]){ // 有圖片時,設定行高為60px; row.setHeightInPoints(60); // 設定圖片所在列寬度為80px,注意這裡單位的一個換算 sheet.setColumnWidth(i, (short) (35.7 * 80)); // sheet.autoSizeColumn(i); byte[] bsValue = (byte[]) value; HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 6, (i+1), (short) 6, (i+1)); anchor.setAnchorType(2); patriarch.createPicture(anchor, workbook.addPicture( bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); }else{ // 其它資料型別都當作字串簡單處理 textValue = value.toString(); } /*if(str!=null) { }else { createRow.createCell(j).setCellValue("");//取出元素 } */ // 如果不是圖片資料,就利用正則表示式判斷textValue是否全部由數字組成 if (textValue != null) { Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 createRow.createCell(j).setCellValue(Double.parseDouble(textValue));//取出元素 } else { HSSFRichTextString richString = new HSSFRichTextString( textValue); HSSFFont font3 = workbook.createFont(); font3.setColor(HSSFColor.BLACK.index); richString.applyFont(font3); createRow.createCell(j).setCellValue(richString); } } j++; }//判斷是否有下一個 } }catch (Exception e){ e.printStackTrace(); }finally{ // 清理資源 } //生成檔案流 HTTPExcle(workbook,response); } /************************************************************(工具方法)***************************************************************/ public static void IOExcle(HSSFWorkbook workbook,String path) { OutputStream out = null; try { out = new FileOutputStream(path.replaceAll("\\\\", "/")+getDateTimeName()+".xls"); workbook.write(out); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }; } public static void HTTPExcle(HSSFWorkbook workbook,HttpServletResponse response) { OutputStream output; try { output = response.getOutputStream(); BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output); bufferedOutPut.flush(); workbook.write(bufferedOutPut); bufferedOutPut.close(); } catch (Exception e) { e.printStackTrace(); } } public static String getDateTimeName() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String format = sdf.format(new Date()); return format; } /** * <p>方法名:nullToEmpty</p> * <p>功能描述:map的value如果是null處理成空字串</p> */ public static List<Map<String, Object>> nullToEmpty(List<Map<String, Object>> list) { if(list !=null && !list.isEmpty()) { for(Map<String, Object> map : list) { Set<String> set = map.keySet(); if(set != null && !set.isEmpty()) { for(String key : set) { if(map.get(key) == null) { map.put(key, ""); } } } } } return list; } }
使用
package com.cpic.caf.template.home.controller; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.net.URLDecoder; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.cpic.caf.template.home.business.ProtocolAppoint; import com.cpic.caf.template.home.entity.OrderEO; import com.cpic.caf.template.home.entity.ProtocolParam; import com.cpic.caf.template.home.service.OrderService; import com.cpic.caf.template.home.util.CommonFunction; import com.cpic.caf.template.home.util.ExportExcel; import com.cpic.caf.template.home.util.HomeSQLUtil; import com.cpic.caf.template.home.util.OrderDSQLUtil; import com.cpic.caf.workers.hall.entity.WorkUserEO; import com.cpic.caf.workers.hall.entity.WorkersCaseuserEO; import com.cpic.caf.workers.hall.service.OmnipotentSqlService; import com.cpic.caf.workers.hall.service.WorkersCaseuserService; /** * 訂單 * * Title: 喜事碼頭 Description: 例子 Copyright: Copyright (c) 2018 * Company:河南意萊享網路科技有限公司 * * @author changshenghui * @version 1.1 * @Date 2018年6月12日 */ @Controller public class OrderController { Logger logger = LoggerFactory.getLogger(OrderController.class); @Autowired OrderService orderService; @Autowired private OmnipotentSqlService omnipotent; @Autowired private WorkersCaseuserService WorkUserEO; /** * 獲得訂單資訊列表(匯出) * * @param model * @param request * @param pageRequest * @return */ @RequestMapping(value = "/getEclise", method = RequestMethod.GET, produces = "application/json") @ResponseBody public void getOrderInfoList(Model model,HttpServletRequest request,HttpSession session,HttpServletResponse response) { ExportExcel<Map<String, Object>> ex = new ExportExcel<Map<String, Object>>(); //建立列 String[] headers = { "主鍵", "從業者ID", "案例是作品集還是婚禮案例", "案例型別", "標題","案例地址","描述","置頂","刪除狀態","訪問量","收藏量", "排序","剩餘可上傳數","婚禮發生時間","建立時間","修改時間"}; //建立值列 List<Map<String, Object>> dataset = omnipotent.findsqlByParam("SELECT * FROM xsmt.ylx_workers_wuorder"); ex.MapExportExcel(headers,dataset,response); System.out.println("excel匯出成功!"); } /** * 獲得訂單資訊列表 * * @param model * @param request * @param pageRequest * @return */ @RequestMapping(value = "/getOrderInfoList", method = RequestMethod.GET, produces = "application/json") @ResponseBody public Map<String, Object> getOrderInfoList(Model model, HttpServletRequest request, HttpSession session, @RequestParam(value="PageIndex",required=false)Integer PageIndex, @RequestParam(value="paramIndex",required=false)Integer paramIndex, @RequestParam(value="start",required=false)Integer start, @RequestParam(value="NO",required=false)String NO, @RequestParam(value="DateParam",required=false)String DateParam, @RequestParam(value="BIZ",required=false)String BIZ ) { try { WorkUserEO attribute =(WorkUserEO) session.getAttribute("worker");//獲取登入物件 Integer WU_id = 1; String NO_ = ""; String SQL = null; String SQLCount = null; if(attribute == null) { System.out.println("- 登入物件為空 -"); }else { WU_id = attribute.getId(); } if(NO!=null) { NO_ = NO; } logger.info("================================="+DateParam+"= 訂單查詢CYZid:"+WU_id+" into getOrderInfoList =========================================="); Map<String, Object> map = new HashMap<String, Object>(); switch (paramIndex) { case 1: //查詢全部訂單 SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ); SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ); System.out.println("查詢全部訂單:"+SQL); break; case 2: //查詢已支付 SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,1,null,null,null,NO_,DateParam,BIZ); SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,1,null,null,null,NO_,DateParam,BIZ); System.out.println("查詢已支付:"+SQL); break; case 3: //查詢待處理 SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,5,null,null,NO_,DateParam,BIZ); SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,5,null,null,NO_,DateParam,BIZ); System.out.println("查詢待處理:"+SQL); break; case 4: //查詢待已付款 SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,1,null,NO_,DateParam,BIZ); SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,1,null,NO_,DateParam,BIZ); System.out.println("查詢待已付款:"+SQL); break; case 5: //查詢已完成 SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,6,null,null,NO_,DateParam,BIZ); SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,6,null,null,NO_,DateParam,BIZ); System.out.println("查詢已完成:"+SQL); break; case 6: //查詢已取消 SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,null,1,NO_,DateParam,BIZ); SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,null,1,NO_,DateParam,BIZ); System.out.println("查詢已取消:"+SQL); break; default: //查詢全部訂單 SQL = OrderDSQLUtil.getOrderListByParams(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ); SQLCount = OrderDSQLUtil.getOrderListByCount(PageIndex,WU_id,null,null,null,null,NO_,DateParam,BIZ); System.out.println("查詢全部訂單:"+SQL); break; } // 查詢資料 List<Map<String, Object>> findsqlByParam = omnipotent.findsqlByParam(SQL); if(start !=null){ // 總條數 List<Map<String, Object>> findsqlByCount = omnipotent.findsqlByParam(SQLCount); map.put("totalCount", findsqlByCount.get(0).get("count")); } map.put("resultList", findsqlByParam); return map; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 增加訂單資訊 * * @param model * @param request * @param pageRequest * @return */ @RequestMapping(value = "/jsonAddOrderInfo", method = RequestMethod.POST) @ResponseBody public ProtocolParam addOrderInfo(Model model, HttpServletRequest request, @RequestParam Map<String, Object> pageRequest) { logger.info("======================================== JsonAddOrderInfo=================================="); // 獲得要新增的欄位 try { String no = URLDecoder.decode((String) pageRequest.get("no"), "utf-8");// 訂單編號 String cust_name = URLDecoder.decode( (String) pageRequest.get("custname"), "utf-8");// 客戶姓名 // 建立實體物件 OrderEO order = new OrderEO(); // 訂單編號 if (no != null && !"".equals(no)) { order.setNo(CommonFunction.getRandomOrderNo()); } // 客戶名稱 if (cust_name != null && !"".equals(cust_name)) { order.setCust_name(cust_name); } // 生成流水號 order.setTrade_no(CommonFunction.GetNewOrderNo(no)); // 服務名稱 order.setService_name("中式"); order.setCreation_time(new Date()); // 呼叫方法 String str = HomeSQLUtil.homeOrderAddSQL(order); int count = orderService.add(str); // orderService.addOrderInfo(order); if (count > 0) { return ProtocolAppoint.succeed("新增成功", null, null); } return null; } catch (UnsupportedEncodingException e) { return ProtocolAppoint.error("新增失敗", null, null); } } /** * 刪除 * * @param pageRequest * @return */ @RequestMapping(value = "/JsonDelOrderInfo", method = RequestMethod.POST) @ResponseBody public ProtocolParam delOrderInfo( @RequestParam Map<String, Object> pageRequest) { logger.info("=============================== JsonDelOrderInfo ==============================="); try { int id = Integer.parseInt(URLDecoder.decode( (String) pageRequest.get("id"), "utf-8")); String sql = HomeSQLUtil.homeDelOrderInfo(id); int count = orderService.delete(sql); if (count > 0) { return ProtocolAppoint.merry(200, "成功", null, null); } return null; } catch (Exception e) { return ProtocolAppoint.error("失敗", null, null); } } @RequestMapping(value="/ModifyOrderInfo",method=RequestMethod.POST) @ResponseBody public ProtocolParam modifyOrderInfo(@RequestParam Map<String, Object> pageRequest){ logger.info("============================= ModifyOrderInfo ========================================="); try { int id=Integer.parseInt(URLDecoder.decode( (String) pageRequest.get("id"), "utf-8")); OrderEO order=new OrderEO(); order.setNo("NO201806201543"); order.setCust_name("青青"); order.setId(BigInteger.valueOf(id)); String sql=HomeSQLUtil.homeModifyOrderInfo(order); int count =orderService.update(sql); if(count>0){ return ProtocolAppoint.merry(200, "成功", null, null); } return null; } catch (Exception e) { return ProtocolAppoint.error("失敗", null, null); } } }