java實(shí)現(xiàn)導(dǎo)出Excel的功能
導(dǎo)出excel是咱Java開(kāi)發(fā)的必備技能啦,之前項(xiàng)目有這個(gè)功能,現(xiàn)在將其獨(dú)立出來(lái),分享一下。
所用技術(shù)就是SpringBoot,然后是MVC架構(gòu)模式。
廢話不多說(shuō),直接上代碼了,源碼點(diǎn)末尾鏈接就可以下載。
(1)新建一個(gè)SpringBoot項(xiàng)目(可以官網(wǎng)https://start.spring.io/直接生成下載,然后導(dǎo)入eclipse),項(xiàng)目結(jié)構(gòu)如下:
(2)修改pom文件,添加依賴;
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- 導(dǎo)出excel --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-contrib --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-contrib</artifactId> <version>3.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.17</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.17</version> </dependency>
(3)新建一個(gè)實(shí)體類,命名為User.java;
package com.twf.springcloud.ExportExcel.po; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = -9180229310895087286L; private String name; // 姓名 private String sex; // 性別 private Integer age; // 年齡 private String phoneNo; // 手機(jī)號(hào) private String address; // 地址 private String hobby; // 愛(ài)好 public User(String name, String sex, Integer age, String phoneNo, String address, String hobby) { super(); this.name = name; this.sex = sex; this.age = age; this.phoneNo = phoneNo; this.address = address; this.hobby = hobby; } 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; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getPhoneNo() { return phoneNo; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getHobby() { return hobby; } public void setHobby(String hobby) { this.hobby = hobby; } @Override public String toString() { return "User [name=" + name + ", sex=" + sex + ", age=" + age + ", phoneNo=" + phoneNo + ", address=" + address + ", hobby=" + hobby + "]"; } }
(4)新建一個(gè)excel樣式工具類;
package com.twf.springcloud.ExportExcel.utils; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; /** * excle樣式工具類 */ public class ExcelFormatUtil { /** * 設(shè)置報(bào)表頭樣式 * @param workbook * @return */ public static CellStyle headSytle(SXSSFWorkbook workbook){ // 設(shè)置style1的樣式,此樣式運(yùn)用在第二行 CellStyle style1 = workbook.createCellStyle();// cell樣式 // 設(shè)置單元格背景色,設(shè)置單元格背景色以下兩句必須同時(shí)設(shè)置 style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 設(shè)置填充樣式 style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 設(shè)置填充色 // 設(shè)置單元格上、下、左、右的邊框線 style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); style1.setBorderLeft(HSSFCellStyle.BORDER_THIN); style1.setBorderRight(HSSFCellStyle.BORDER_THIN); style1.setBorderTop(HSSFCellStyle.BORDER_THIN); Font font1 = workbook.createFont();// 創(chuàng)建一個(gè)字體對(duì)象 font1.setBoldweight((short) 10);// 設(shè)置字體的寬度 font1.setFontHeightInPoints((short) 10);// 設(shè)置字體的高度 font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗體顯示 style1.setFont(font1);// 設(shè)置style1的字體 style1.setWrapText(true);// 設(shè)置自動(dòng)換行 style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設(shè)置單元格字體顯示居中(左右方向) style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 設(shè)置單元格字體顯示居中(上下方向) return style1; } /** * 設(shè)置報(bào)表體樣式 * @param wb * @return */ public static CellStyle contentStyle(SXSSFWorkbook wb){ // 設(shè)置style1的樣式,此樣式運(yùn)用在第二行 CellStyle style1 = wb.createCellStyle();// cell樣式 // 設(shè)置單元格上、下、左、右的邊框線 style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); style1.setBorderLeft(HSSFCellStyle.BORDER_THIN); style1.setBorderRight(HSSFCellStyle.BORDER_THIN); style1.setBorderTop(HSSFCellStyle.BORDER_THIN); style1.setWrapText(true);// 設(shè)置自動(dòng)換行 style1.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 設(shè)置單元格字體顯示居中(左右方向) style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 設(shè)置單元格字體顯示居中(上下方向) return style1; } /** * 設(shè)置報(bào)表標(biāo)題樣式 * @param workbook * @return */ public static HSSFCellStyle titleSytle(HSSFWorkbook workbook,short color,short fontSize){ // 設(shè)置style1的樣式,此樣式運(yùn)用在第二行 HSSFCellStyle style1 = workbook.createCellStyle();// cell樣式 // 設(shè)置單元格背景色,設(shè)置單元格背景色以下兩句必須同時(shí)設(shè)置 //style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 設(shè)置填充樣式 //short fcolor = color; if(color != HSSFColor.WHITE.index){ style1.setFillForegroundColor(color);// 設(shè)置填充色 } // 設(shè)置單元格上、下、左、右的邊框線 style1.setBorderBottom(HSSFCellStyle.BORDER_THIN); style1.setBorderLeft(HSSFCellStyle.BORDER_THIN); style1.setBorderRight(HSSFCellStyle.BORDER_THIN); style1.setBorderTop(HSSFCellStyle.BORDER_THIN); HSSFFont font1 = workbook.createFont();// 創(chuàng)建一個(gè)字體對(duì)象 font1.setBoldweight(fontSize);// 設(shè)置字體的寬度 font1.setFontHeightInPoints(fontSize);// 設(shè)置字體的高度 font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 粗體顯示 style1.setFont(font1);// 設(shè)置style1的字體 style1.setWrapText(true);// 設(shè)置自動(dòng)換行 style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 設(shè)置單元格字體顯示居中(左右方向) style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 設(shè)置單元格字體顯示居中(上下方向) return style1; } /** *設(shè)置表頭 * @param sheet */ public static void initTitleEX(SXSSFSheet sheet, CellStyle header,String title[],int titleLength[]) { SXSSFRow row0 = sheet.createRow(0); row0.setHeight((short) 800); for(int j = 0;j<title.length; j++) { SXSSFCell cell = row0.createCell(j); //設(shè)置每一列的字段名 cell.setCellValue(title[j]); cell.setCellStyle(header); sheet.setColumnWidth(j, titleLength[j]); } } }
(5)新建一個(gè)Service接口;
package com.twf.springcloud.ExportExcel.sevice; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.http.ResponseEntity; public interface ExportService { ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response); }
(6)新建一個(gè)Service接口實(shí)現(xiàn)類;
package com.twf.springcloud.ExportExcel.sevice.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.xssf.streaming.SXSSFCell; import org.apache.poi.xssf.streaming.SXSSFRow; import org.apache.poi.xssf.streaming.SXSSFSheet; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import com.twf.springcloud.ExportExcel.controller.BaseFrontController; import com.twf.springcloud.ExportExcel.po.User; import com.twf.springcloud.ExportExcel.sevice.ExportService; import com.twf.springcloud.ExportExcel.utils.ExcelFormatUtil; @Service public class ExportServiceImpl implements ExportService{ Logger logger = LoggerFactory.getLogger(ExportServiceImpl.class); @Override public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) { try { logger.info(">>>>>>>>>>開(kāi)始導(dǎo)出excel>>>>>>>>>>"); // 造幾條數(shù)據(jù) List<User> list = new ArrayList<>(); list.add(new User("唐三藏", "男", 30, "13411111111", "東土大唐", "取西經(jīng)")); list.add(new User("孫悟空", "男", 29, "13411111112", "菩提院", "打妖怪")); list.add(new User("豬八戒", "男", 28, "13411111113", "高老莊", "偷懶")); list.add(new User("沙悟凈", "男", 27, "13411111114", "流沙河", "挑擔(dān)子")); BaseFrontController baseFrontController = new BaseFrontController(); return baseFrontController.buildResponseEntity(export((List<User>) list), "用戶表.xls"); } catch (Exception e) { e.printStackTrace(); logger.error(">>>>>>>>>>導(dǎo)出excel 異常,原因?yàn)椋? + e.getMessage()); } return null; } private InputStream export(List<User> list) { logger.info(">>>>>>>>>>>>>>>>>>>>開(kāi)始進(jìn)入導(dǎo)出方法>>>>>>>>>>"); ByteArrayOutputStream output = null; InputStream inputStream1 = null; SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000條數(shù)據(jù)在內(nèi)存中 SXSSFSheet sheet = wb.createSheet(); // 設(shè)置報(bào)表頭樣式 CellStyle header = ExcelFormatUtil.headSytle(wb);// cell樣式 CellStyle content = ExcelFormatUtil.contentStyle(wb);// 報(bào)表體樣式 // 每一列字段名 String[] strs = new String[] { "姓名", "性別", "年齡", "手機(jī)號(hào)", "地址","愛(ài)好" }; // 字段名所在表格的寬度 int[] ints = new int[] { 5000, 5000, 5000, 5000, 5000, 5000 }; // 設(shè)置表頭樣式 ExcelFormatUtil.initTitleEX(sheet, header, strs, ints); logger.info(">>>>>>>>>>>>>>>>>>>>表頭樣式設(shè)置完成>>>>>>>>>>"); if (list != null && list.size() > 0) { logger.info(">>>>>>>>>>>>>>>>>>>>開(kāi)始遍歷數(shù)據(jù)組裝單元格內(nèi)容>>>>>>>>>>"); for (int i = 0; i < list.size(); i++) { User user = list.get(i); SXSSFRow row = sheet.createRow(i + 1); int j = 0; SXSSFCell cell = row.createCell(j++); cell.setCellValue(user.getName()); // 姓名 cell.setCellStyle(content); cell = row.createCell(j++); cell.setCellValue(user.getSex()); // 性別 cell.setCellStyle(content); cell = row.createCell(j++); cell.setCellValue(user.getAge()); // 年齡 cell.setCellStyle(content); cell = row.createCell(j++); cell.setCellValue(user.getPhoneNo()); // 手機(jī)號(hào) cell.setCellStyle(content); cell = row.createCell(j++); cell.setCellValue(user.getAddress()); // 地址 cell.setCellStyle(content); cell = row.createCell(j++); cell.setCellValue(user.getHobby()); // 愛(ài)好 cell.setCellStyle(content); } logger.info(">>>>>>>>>>>>>>>>>>>>結(jié)束遍歷數(shù)據(jù)組裝單元格內(nèi)容>>>>>>>>>>"); } try { output = new ByteArrayOutputStream(); wb.write(output); inputStream1 = new ByteArrayInputStream(output.toByteArray()); output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (output != null) { output.close(); if (inputStream1 != null) inputStream1.close(); } } catch (IOException e) { e.printStackTrace(); } } return inputStream1; } }
(7)新建一個(gè)下載文件的通用controller;
package com.twf.springcloud.ExportExcel.controller; import java.io.InputStream; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import org.apache.poi.util.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.validation.annotation.Validated; @Validated public class BaseFrontController { /** * slf4j 日志 logger */ protected final Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 下載文件,純SpringMVC的API來(lái)完成 * * @param is 文件輸入流 * @param name 文件名稱,帶后綴名 * * @throws Exception */ public ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception { logger.info(">>>>>>>>>>>>>>>>>>>>開(kāi)始下載文件>>>>>>>>>>"); if (this.logger.isDebugEnabled()) this.logger.debug("download: " + name); HttpHeaders header = new HttpHeaders(); String fileSuffix = name.substring(name.lastIndexOf('.') + 1); fileSuffix = fileSuffix.toLowerCase(); Map<String, String> arguments = new HashMap<String, String>(); arguments.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); arguments.put("xls", "application/vnd.ms-excel"); String contentType = arguments.get(fileSuffix); header.add("Content-Type", (StringUtils.hasText(contentType) ? contentType : "application/x-download")); if(is!=null && is.available()!=0){ header.add("Content-Length", String.valueOf(is.available())); header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8")); byte[] bs = IOUtils.toByteArray(is); logger.info(">>>>>>>>>>>>>>>>>>>>結(jié)束下載文件-有記錄>>>>>>>>>>"); logger.info(">>>>>>>>>>結(jié)束導(dǎo)出excel>>>>>>>>>>"); return new ResponseEntity<>(bs, header, HttpStatus.OK); }else{ String string="數(shù)據(jù)為空"; header.add("Content-Length", "0"); header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8")); logger.info(">>>>>>>>>>>>>>>>>>>>結(jié)束下載文件-無(wú)記錄>>>>>>>>>>"); logger.info(">>>>>>>>>>結(jié)束導(dǎo)出excel>>>>>>>>>>"); return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK); } } }
(8)新建一個(gè)controller,作為請(qǐng)求的入口;
package com.twf.springcloud.ExportExcel.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.twf.springcloud.ExportExcel.sevice.ExportService; @RestController @RequestMapping("/exportExcel/") public class ExportController { @Autowired private ExportService exportService; // 導(dǎo)出excel @RequestMapping("exportExcel") public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) { return exportService.exportExcel(request,response); } }
(9)運(yùn)行ExportExcelApplication,瀏覽器訪問(wèn)http://localhost:8080/exportExcel/exportExcel,可以下載excel,打開(kāi)如下:
(10)項(xiàng)目源碼
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
淺談java對(duì)象之間相互轉(zhuǎn)化的多種方式
這篇文章主要介紹了淺談java對(duì)象之間相互轉(zhuǎn)化的多種方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08關(guān)于MyBatis 查詢數(shù)據(jù)時(shí)屬性中多對(duì)一的問(wèn)題(多條數(shù)據(jù)對(duì)應(yīng)一條數(shù)據(jù))
這篇文章主要介紹了MyBatis 查詢數(shù)據(jù)時(shí)屬性中多對(duì)一的問(wèn)題(多條數(shù)據(jù)對(duì)應(yīng)一條數(shù)據(jù)),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01Spring boot項(xiàng)目redisTemplate實(shí)現(xiàn)輕量級(jí)消息隊(duì)列的方法
這篇文章主要給大家介紹了關(guān)于Spring boot項(xiàng)目redisTemplate實(shí)現(xiàn)輕量級(jí)消息隊(duì)列的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04java Struts2框架下實(shí)現(xiàn)文件上傳功能
這篇文章主要為大家詳細(xì)介紹了java Struts2框架下實(shí)現(xiàn)文件上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10Java數(shù)組與二維數(shù)組及替換空格實(shí)戰(zhàn)真題講解
數(shù)組對(duì)于每一門編程語(yǔ)言來(lái)說(shuō)都是重要的數(shù)據(jù)結(jié)構(gòu)之一,當(dāng)然不同語(yǔ)言對(duì)數(shù)組的實(shí)現(xiàn)及處理也不盡相同。Java?語(yǔ)言中提供的數(shù)組是用來(lái)存儲(chǔ)固定大小的同類型元素,這篇文章主要介紹了Java數(shù)組與二維數(shù)組及替換空格實(shí)戰(zhàn)真題講解2022-07-07如何把springboot jar項(xiàng)目 改為war項(xiàng)目
這篇文章主要介紹了如何把springboot jar項(xiàng)目 改為war項(xiàng)目,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11SpringBoot中的@PostConstruct注解詳細(xì)解析
這篇文章主要介紹了SpringBoot中的@PostConstruct注解詳細(xì)解析,@PostConstruct注解,主要用于在Spring容器啟動(dòng)時(shí)執(zhí)行某些操作或者任務(wù),@PostConstruct注解一般放在BEAN的方法上,一旦BEAN初始化完成之后,將會(huì)調(diào)用這個(gè)方法,需要的朋友可以參考下2024-01-01