Java導(dǎo)出Excel通用工具類實(shí)例代碼
一、概述
相信大家在工作過程中,都會(huì)遇到這樣一個(gè)需求,就是將相關(guān)的數(shù)據(jù)列表導(dǎo)出成excel,那么,有沒有通用的導(dǎo)出方式呢,這里,就帶著大家一起來用Java實(shí)現(xiàn)一個(gè)通用的導(dǎo)出Excel的工具。
二、項(xiàng)目實(shí)現(xiàn)
1、構(gòu)建pom.xml
我們的工程是利用Maven來構(gòu)建的,項(xiàng)目具體搭建過程大家可以參見網(wǎng)上其他資料,這里我們僅給出最核心的Maven配置
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.11-beta2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.11-beta2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.11-beta2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-excelant</artifactId> <version>3.11-beta2</version> </dependency>
2、編寫ExportExcelUtil類
這個(gè)類使我們整個(gè)工具的核心,它實(shí)現(xiàn)了Excel文件的導(dǎo)出功能,具體代碼如下:
package com.lyz.utils.excel.poi; 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.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; 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.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; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRichTextString; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * 導(dǎo)出Excel * @author liuyazhuang * * @param <T> */ public class ExportExcelUtil<T>{ // 2007 版本以上 最大支持1048576行 public final static String EXCEl_FILE_2007 = "2007"; // 2003 版本 最大支持65536 行 public final static String EXCEL_FILE_2003 = "2003"; /** * <p> * 導(dǎo)出無頭部標(biāo)題行Excel <br> * 時(shí)間格式默認(rèn):yyyy-MM-dd hh:mm:ss <br> * </p> * * @param title 表格標(biāo)題 * @param dataset 數(shù)據(jù)集合 * @param out 輸出流 * @param version 2003 或者 2007,不傳時(shí)默認(rèn)生成2003版本 */ public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) { if(StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())){ exportExcel2003(title, null, dataset, out, "yyyy-MM-dd HH:mm:ss"); }else{ exportExcel2007(title, null, dataset, out, "yyyy-MM-dd HH:mm:ss"); } } /** * <p> * 導(dǎo)出帶有頭部標(biāo)題行的Excel <br> * 時(shí)間格式默認(rèn):yyyy-MM-dd hh:mm:ss <br> * </p> * * @param title 表格標(biāo)題 * @param headers 頭部標(biāo)題集合 * @param dataset 數(shù)據(jù)集合 * @param out 輸出流 * @param version 2003 或者 2007,不傳時(shí)默認(rèn)生成2003版本 */ public void exportExcel(String title,String[] headers, Collection<T> dataset, OutputStream out,String version) { if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){ exportExcel2003(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss"); }else{ exportExcel2007(title, headers, dataset, out, "yyyy-MM-dd HH:mm:ss"); } } /** * <p> * 通用Excel導(dǎo)出方法,利用反射機(jī)制遍歷對象的所有字段,將數(shù)據(jù)寫入Excel文件中 <br> * 此版本生成2007以上版本的文件 (文件后綴:xlsx) * </p> * * @param title * 表格標(biāo)題名 * @param headers * 表格頭部標(biāo)題集合 * @param dataset * 需要顯示的數(shù)據(jù)集合,集合中一定要放置符合JavaBean風(fēng)格的類的對象。此方法支持的 * JavaBean屬性的數(shù)據(jù)類型有基本數(shù)據(jù)類型及String,Date * @param out * 與輸出設(shè)備關(guān)聯(lián)的流對象,可以將EXCEL文檔導(dǎo)出到本地文件或者網(wǎng)絡(luò)中 * @param pattern * 如果有時(shí)間數(shù)據(jù),設(shè)定輸出格式。默認(rèn)為"yyyy-MM-dd hh:mm:ss" */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) { // 聲明一個(gè)工作薄 XSSFWorkbook workbook = new XSSFWorkbook(); // 生成一個(gè)表格 XSSFSheet sheet = workbook.createSheet(title); // 設(shè)置表格默認(rèn)列寬度為15個(gè)字節(jié) sheet.setDefaultColumnWidth(20); // 生成一個(gè)樣式 XSSFCellStyle style = workbook.createCellStyle(); // 設(shè)置這些樣式 style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray)); style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(XSSFCellStyle.BORDER_THIN); style.setBorderLeft(XSSFCellStyle.BORDER_THIN); style.setBorderRight(XSSFCellStyle.BORDER_THIN); style.setBorderTop(XSSFCellStyle.BORDER_THIN); style.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 生成一個(gè)字體 XSSFFont font = workbook.createFont(); font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setColor(new XSSFColor(java.awt.Color.BLACK)); font.setFontHeightInPoints((short) 11); // 把字體應(yīng)用到當(dāng)前的樣式 style.setFont(font); // 生成并設(shè)置另一個(gè)樣式 XSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE)); style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(XSSFCellStyle.BORDER_THIN); style2.setBorderLeft(XSSFCellStyle.BORDER_THIN); style2.setBorderRight(XSSFCellStyle.BORDER_THIN); style2.setBorderTop(XSSFCellStyle.BORDER_THIN); style2.setAlignment(XSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); // 生成另一個(gè)字體 XSSFFont font2 = workbook.createFont(); font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL); // 把字體應(yīng)用到當(dāng)前的樣式 style2.setFont(font2); // 產(chǎn)生表格標(biāo)題行 XSSFRow row = sheet.createRow(0); XSSFCell cellHeader; for (int i = 0; i < headers.length; i++) { cellHeader = row.createCell(i); cellHeader.setCellStyle(style); cellHeader.setCellValue(new XSSFRichTextString(headers[i])); } // 遍歷集合數(shù)據(jù),產(chǎn)生數(shù)據(jù)行 Iterator<T> it = dataset.iterator(); int index = 0; T t; Field[] fields; Field field; XSSFRichTextString richString; Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher; String fieldName; String getMethodName; XSSFCell cell; Class tCls; Method getMethod; Object value; String textValue; SimpleDateFormat sdf = new SimpleDateFormat(pattern); while (it.hasNext()) { index++; row = sheet.createRow(index); t = (T) it.next(); // 利用反射,根據(jù)JavaBean屬性的先后順序,動(dòng)態(tài)調(diào)用getXxx()方法得到屬性值 fields = t.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { cell = row.createCell(i); cell.setCellStyle(style2); field = fields[i]; fieldName = field.getName(); getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { tCls = t.getClass(); getMethod = tCls.getMethod(getMethodName, new Class[] {}); value = getMethod.invoke(t, new Object[] {}); // 判斷值的類型后進(jìn)行強(qiáng)制類型轉(zhuǎn)換 textValue = null; if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Float) { textValue = String.valueOf((Float) value); cell.setCellValue(textValue); } else if (value instanceof Double) { textValue = String.valueOf((Double) value); cell.setCellValue(textValue); } else if (value instanceof Long) { cell.setCellValue((Long) value); } if (value instanceof Boolean) { textValue = "是"; if (!(Boolean) value) { textValue = "否"; } } else if (value instanceof Date) { textValue = sdf.format((Date) value); } else { // 其它數(shù)據(jù)類型都當(dāng)作字符串簡單處理 if (value != null) { textValue = value.toString(); } } if (textValue != null) { matcher = p.matcher(textValue); if (matcher.matches()) { // 是數(shù)字當(dāng)作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { richString = new XSSFRichTextString(textValue); 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 { // 清理資源 } } } try { workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } /** * <p> * 通用Excel導(dǎo)出方法,利用反射機(jī)制遍歷對象的所有字段,將數(shù)據(jù)寫入Excel文件中 <br> * 此方法生成2003版本的excel,文件名后綴:xls <br> * </p> * * @param title * 表格標(biāo)題名 * @param headers * 表格頭部標(biāo)題集合 * @param dataset * 需要顯示的數(shù)據(jù)集合,集合中一定要放置符合JavaBean風(fēng)格的類的對象。此方法支持的 * JavaBean屬性的數(shù)據(jù)類型有基本數(shù)據(jù)類型及String,Date * @param out * 與輸出設(shè)備關(guān)聯(lián)的流對象,可以將EXCEL文檔導(dǎo)出到本地文件或者網(wǎng)絡(luò)中 * @param pattern * 如果有時(shí)間數(shù)據(jù),設(shè)定輸出格式。默認(rèn)為"yyyy-MM-dd hh:mm:ss" */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void exportExcel2003(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) { // 聲明一個(gè)工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個(gè)表格 HSSFSheet sheet = workbook.createSheet(title); // 設(shè)置表格默認(rèn)列寬度為15個(gè)字節(jié) sheet.setDefaultColumnWidth(20); // 生成一個(gè)樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設(shè)置這些樣式 style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.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); // 生成一個(gè)字體 HSSFFont font = workbook.createFont(); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); font.setFontName("宋體"); font.setColor(HSSFColor.WHITE.index); font.setFontHeightInPoints((short) 11); // 把字體應(yīng)用到當(dāng)前的樣式 style.setFont(font); // 生成并設(shè)置另一個(gè)樣式 HSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.WHITE.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); // 生成另一個(gè)字體 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 把字體應(yīng)用到當(dāng)前的樣式 style2.setFont(font2); // 產(chǎn)生表格標(biāo)題行 HSSFRow row = sheet.createRow(0); HSSFCell cellHeader; for (int i = 0; i < headers.length; i++) { cellHeader = row.createCell(i); cellHeader.setCellStyle(style); cellHeader.setCellValue(new HSSFRichTextString(headers[i])); } // 遍歷集合數(shù)據(jù),產(chǎn)生數(shù)據(jù)行 Iterator<T> it = dataset.iterator(); int index = 0; T t; Field[] fields; Field field; HSSFRichTextString richString; Pattern p = Pattern.compile("^//d+(//.//d+)?$"); Matcher matcher; String fieldName; String getMethodName; HSSFCell cell; Class tCls; Method getMethod; Object value; String textValue; SimpleDateFormat sdf = new SimpleDateFormat(pattern); while (it.hasNext()) { index++; row = sheet.createRow(index); t = (T) it.next(); // 利用反射,根據(jù)JavaBean屬性的先后順序,動(dòng)態(tài)調(diào)用getXxx()方法得到屬性值 fields = t.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { cell = row.createCell(i); cell.setCellStyle(style2); field = fields[i]; fieldName = field.getName(); getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { tCls = t.getClass(); getMethod = tCls.getMethod(getMethodName, new Class[] {}); value = getMethod.invoke(t, new Object[] {}); // 判斷值的類型后進(jìn)行強(qiáng)制類型轉(zhuǎn)換 textValue = null; if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Float) { textValue = String.valueOf((Float) value); cell.setCellValue(textValue); } else if (value instanceof Double) { textValue = String.valueOf((Double) value); cell.setCellValue(textValue); } else if (value instanceof Long) { cell.setCellValue((Long) value); } if (value instanceof Boolean) { textValue = "是"; if (!(Boolean) value) { textValue = "否"; } } else if (value instanceof Date) { textValue = sdf.format((Date) value); } else { // 其它數(shù)據(jù)類型都當(dāng)作字符串簡單處理 if (value != null) { textValue = value.toString(); } } if (textValue != null) { matcher = p.matcher(textValue); if (matcher.matches()) { // 是數(shù)字當(dāng)作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { richString = new HSSFRichTextString(textValue); 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 { // 清理資源 } } } try { workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } }
為了演示導(dǎo)出功能,這里我們創(chuàng)建了一個(gè)Student學(xué)生類。
3、創(chuàng)建Student類
package com.lyz.utils.excel.poi; /** * 例子JavaBean * @author liuyazhuang * */ public class Student { private int id; private String name; private String sex; public Student(int id, String name, String sex) { this.id = id; this.name = name; this.sex = sex; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
4、創(chuàng)建測試類TestExportExcelUtil
這個(gè)類,主要是用來測試我們的工具類。具體代碼如下:
package com.lyz.test; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import com.lyz.utils.excel.poi.ExportExcelUtil; import com.lyz.utils.excel.poi.Student; /** * 測試文件導(dǎo)出 * @author liuyazhuang * */ public class TestExportExcelUtil { public static void main(String[] args) throws Exception{ ExportExcelUtil<Student> util = new ExportExcelUtil<Student>(); // 準(zhǔn)備數(shù)據(jù) List<Student> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(new Student(111,"張三asdf","男")); list.add(new Student(111,"李四asd","男")); list.add(new Student(111,"王五","女")); } String[] columnNames = { "ID", "姓名", "性別" }; util.exportExcel("用戶導(dǎo)出", columnNames, list, new FileOutputStream("E:/test.xls"), ExportExcelUtil.EXCEL_FILE_2003); } }
5、測試
我們運(yùn)行TestExportExcelUtil類,會(huì)發(fā)現(xiàn)在我們的E盤下生成了test.xls文件,具體如下:
三、項(xiàng)目擴(kuò)展
以上實(shí)現(xiàn)均是在本地磁盤生成excel文件,但更多的時(shí)候,我們需要通過點(diǎn)擊網(wǎng)頁上的某個(gè)按鈕來自動(dòng)生成并下載Excel文檔,那么,這又如何實(shí)現(xiàn)呢?下面我們就一起來實(shí)現(xiàn)這個(gè)功能。
1、擴(kuò)展ExportExcelUtil類
根據(jù)Java的繼承思想,我們不在ExportExcelUtil類上修改添加,我們創(chuàng)建一個(gè)ExportExcelUtil類的子類ExportExcelWrapper,這個(gè)類繼承ExportExcelUtil的所有功能,同時(shí),擴(kuò)展了網(wǎng)頁生成Excel的功能。具體代碼如下:
package com.lyz.utils.excel.poi; import java.net.URLEncoder; import java.util.Collection; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringUtils; /** * 包裝類 * @author liuyazhuang * * @param <T> */ public class ExportExcelWrapper<T> extends ExportExcelUtil<T> { /** * <p> * 導(dǎo)出帶有頭部標(biāo)題行的Excel <br> * 時(shí)間格式默認(rèn):yyyy-MM-dd hh:mm:ss <br> * </p> * * @param title 表格標(biāo)題 * @param headers 頭部標(biāo)題集合 * @param dataset 數(shù)據(jù)集合 * @param out 輸出流 * @param version 2003 或者 2007,不傳時(shí)默認(rèn)生成2003版本 */ public void exportExcel(String fileName, String title, String[] headers, Collection<T> dataset, HttpServletResponse response,String version) { try { response.setContentType("application/vnd.ms-excel"); response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".xls"); if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){ exportExcel2003(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss"); }else{ exportExcel2007(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss"); } } catch (Exception e) { e.printStackTrace(); } } }
這樣,我們可以在Controller層調(diào)用ExportExcelWrapper將相關(guān)的數(shù)據(jù)和HttpServletResponse傳遞進(jìn)來,即可實(shí)現(xiàn)通過網(wǎng)頁生生并下載Excel文檔了。
2、編寫Controller類
@Controller("test") @RequestMapping("/test") public class TestController { @RequestMapping("/get/excel") public void getExcel(HttpServletRequest request, HttpServletResponse response) throws Exception { // 準(zhǔn)備數(shù)據(jù) List<Student> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(new Student(111,"張三asdf","男")); list.add(new Student(111,"李四asd","男")); list.add(new Student(111,"王五","女")); } String[] columnNames = { "ID", "姓名", " 性別"}; String fileName = "excel1"; ExportExcelWrapper<Student> util = new ExportExcelWrapper<Student>(); util.exportExcel(fileName, fileName, columnNames, list, response, ExportExcelUtil.EXCEL_FILE_2003); } }
3、編寫index.html
這個(gè)網(wǎng)頁很簡單,具體實(shí)現(xiàn)如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>導(dǎo)出Excel</title> </head> <body> <form id="form_login" action="http://127.0.0.1:8080/test/get/excel" method="post"> </form> <button id="btn-submit" onclick="beforeSubmit()">Submit</button> <script type="text/javascript"> var loginForm = document.getElementById('form_login'); function beforeSubmit() { loginForm.submit(); } </script> </body> </html>
4、測試
我們將程序發(fā)布到Tomcat,并點(diǎn)擊網(wǎng)上的按鈕,效果如下:
我們打開excel1.xls文件如下:
至此,我們的工具就編寫完成了。
總結(jié)
到此這篇關(guān)于Java導(dǎo)出Excel通用工具類的文章就介紹到這了,更多相關(guān)Java導(dǎo)出Excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(14)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-07-07Mybatis-Plus進(jìn)階分頁與樂觀鎖插件及通用枚舉和多數(shù)據(jù)源詳解
這篇文章主要介紹了Mybatis-Plus的分頁插件與樂觀鎖插件還有通用枚舉和多數(shù)據(jù)源的相關(guān)介紹,文中代碼附有詳細(xì)的注釋,感興趣的朋友來看看吧2022-03-03SpringBoot整合mybatis結(jié)合pageHelper插件實(shí)現(xiàn)分頁
在本篇文章里小編給大家整理的是關(guān)于SpringBoot整合mybatis使用pageHelper插件進(jìn)行分頁操作相關(guān)知識點(diǎn),需要的朋友們學(xué)習(xí)下。2020-02-02