Java實(shí)現(xiàn)多個(gè)sheet頁(yè)數(shù)據(jù)導(dǎo)出功能
前言
大概內(nèi)容:
自定義格式的標(biāo)題,及對(duì)應(yīng)的數(shù)據(jù),每個(gè)sheet頁(yè)的表頭及數(shù)據(jù)都可以不同,具體根據(jù)實(shí)際業(yè)務(wù)去變更,可以仿照這個(gè)例子去編寫(xiě),這里提供的是最基礎(chǔ)的多sheet頁(yè)導(dǎo)出,如果需要多行表頭復(fù)雜業(yè)務(wù)的多sheet頁(yè)導(dǎo)出可參考我另一篇復(fù)雜表頭,多行表頭導(dǎo)出,如果導(dǎo)出不確定行數(shù)列數(shù)跟隨業(yè)務(wù)的增長(zhǎng)而變動(dòng)的導(dǎo)出參考另一篇不確定行數(shù)列數(shù)數(shù)據(jù)的工具類(lèi)
提示:以下是導(dǎo)出到本地,工具類(lèi)也有導(dǎo)出到瀏覽器的封裝方法,可直接使用
一、實(shí)現(xiàn)的效果
本篇測(cè)試數(shù)據(jù)為兩個(gè)sheet頁(yè)的導(dǎo)出功能,測(cè)試中導(dǎo)出到本地,工具類(lèi)有導(dǎo)出到瀏覽器的封裝方法,可直接使用
二、調(diào)用工具類(lèi)
業(yè)務(wù)層調(diào)用
//假設(shè)這是需要導(dǎo)出的數(shù)據(jù) public static void main(String[] args) { /** 第一頁(yè)數(shù)據(jù) */ List<String[]> dataAllOne = new ArrayList<>(); String[] data1 = (String[]) Arrays.asList("楊1", "18", "男").toArray(); String[] data2 = (String[]) Arrays.asList("楊2", "19", "女").toArray(); dataAllOne.add(data1); dataAllOne.add(data2); /** 第二頁(yè)數(shù)據(jù) */ List<String[]> dataAllTwo = new ArrayList<>(); String[] data3 = (String[]) Arrays.asList("駕照", "2022年9月5日10:08:46", "是").toArray(); String[] data4 = (String[]) Arrays.asList("戶(hù)口本", "2022-9-5 10:09:01", "否").toArray(); dataAllTwo.add(data3); dataAllTwo.add(data4); ArrayList<ExcelExp> list = new ArrayList<>(); ExcelExp excelExp1 = new ExcelExp("存放人員信息", (String[]) Arrays.asList("姓名", "年齡", "性別").toArray(), dataAllOne, "人員信息"); ExcelExp excelExp2 = new ExcelExp("存放文件信息", (String[]) Arrays.asList("文件名稱(chēng)", "上傳時(shí)間", "是否上傳到FDFS").toArray(), dataAllTwo, "文件上傳情況"); list.add(excelExp1); list.add(excelExp2); Workbook workbook = ExcelExportUtil.exportManySheetExcel(list); //導(dǎo)出數(shù)據(jù)到excel FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream("F:/新建文件夾/demo.xls"); workbook.write(fileOutputStream); fileOutputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(fileOutputStream != null){ try { fileOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }
三、詳細(xì)工具類(lèi)
直接copy改吧改吧就可以使用,有詳細(xì)注釋
import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * @Description: java導(dǎo)出功能(多個(gè)sheet頁(yè)數(shù)據(jù)導(dǎo)出) * * @Author: 楊永卓 * @Date: 2022/9/5 10:31 */ public final class ExcelExportUtil { private ExcelExportUtil (){} private static ExcelExportUtil excelExportUtil = null; static{ /** 類(lèi)加載時(shí)創(chuàng)建,只會(huì)創(chuàng)建一個(gè)對(duì)象 */ if(excelExportUtil == null) excelExportUtil = new ExcelExportUtil (); } /** * @param @param file 導(dǎo)出文件路徑 * @param @param mysheets * @return void * @throws * @Title: exportManySheetExcel * @Description: 可生成單個(gè)、多個(gè)sheet */ public static Workbook exportManySheetExcel(List<ExcelExp> mysheets) { HSSFWorkbook wb = new HSSFWorkbook();// 創(chuàng)建工作薄 List<ExcelExp> sheets = mysheets; // 表頭樣式 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); // 創(chuàng)建一個(gè)居中格式 // 字體樣式 HSSFFont fontStyle = wb.createFont(); fontStyle.setFontName("微軟雅黑"); fontStyle.setFontHeightInPoints((short) 12); // fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); style.setFont(fontStyle); for (ExcelExp excel : sheets) { // 新建一個(gè)sheet HSSFSheet sheet = wb.createSheet(excel.getFileName());// 獲取該sheet名稱(chēng) String[] handers = excel.getHanders();// 獲取sheet的標(biāo)題名 HSSFRow tableName = sheet.createRow(0); HSSFCell cellName = tableName.createCell(0); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9)); HSSFCellStyle titleStyle = wb.createCellStyle(); // 設(shè)置單元格樣式 HSSFFont titleFont = wb.createFont(); // 標(biāo)題字體 titleFont.setFontHeightInPoints((short) 16); // 字號(hào) titleStyle.setFont(titleFont); titleStyle.setAlignment(HorizontalAlignment.CENTER); cellName.setCellStyle(titleStyle); // 設(shè)置單元格內(nèi)容 cellName.setCellValue(excel.getTableName()); HSSFRow rowFirst = sheet.createRow(1);// 第一個(gè)sheet的第一行為標(biāo)題 // 寫(xiě)標(biāo)題 for (int i = 0; i < handers.length; i++) { // 獲取第一行的每個(gè)單元格 HSSFCell cell = rowFirst.createCell(i); // 往單元格里寫(xiě)數(shù)據(jù) cell.setCellValue(handers[i]); cell.setCellStyle(style); // 加樣式 sheet.setColumnWidth(i, 4000); // 設(shè)置每列的列寬 } // 寫(xiě)數(shù)據(jù)集 List<String[]> dataset = excel.getDataset(); for (int i = 0; i < dataset.size(); i++) { String[] data = dataset.get(i);// 獲取該對(duì)象 // 創(chuàng)建數(shù)據(jù)行 HSSFRow row = sheet.createRow(i + 2); for (int j = 0; j < data.length; j++) { // 設(shè)置對(duì)應(yīng)單元格的值 row.createCell(j).setCellValue(data[j]); } } } return wb; } /** * @Description: [方法1:導(dǎo)出到瀏覽器] * @Param: [fileName, wb, response] * @return: void * @Author: yangyongzhuo * @Date: 2022/7/25 9:40 */ private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) { try { response.setContentType("application/octet-stream"); // 可自行定義編碼格式 response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8")); // 清除jsp編譯html文件的空白,防止excel出現(xiàn)空行 response.flushBuffer(); // 寫(xiě)出 wb.write(response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(wb); } } /** * @Description: [方法2:導(dǎo)出到瀏覽器] * @Param: [fileName, wb, response,request] * @return: void * @Author: yangyongzhuo * @Date: 2022/7/25 9:40 */ public static void outputXls(Workbook workbook, String fileName, HttpServletResponse response, HttpServletRequest request) { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { workbook.write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 設(shè)置response參數(shù),可以打開(kāi)下載頁(yè)面 response.reset(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + encodeFileName(fileName + ".xls", request)); ServletOutputStream out = response.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; // Simple read/write loop. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } catch (Exception e1) { e1.printStackTrace(); } } public static String encodeFileName(String fileName, HttpServletRequest request) throws UnsupportedEncodingException { String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) { return URLEncoder.encode(fileName, "UTF-8"); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { return "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(fileName.getBytes("UTF-8")))) + "?="; } else { return fileName; } } /** * 把list<map>封裝成list<String[]> 由于我的結(jié)果集是List<Map<String,Object>>,所以我寫(xiě)了這個(gè)個(gè)方法,把它轉(zhuǎn)換成List<String[]> * * @param list 要封裝的list * @param strKey String[]的長(zhǎng)度 * @return */ public static List<String[]> listUtils(List<Map<String, Object>> list, String[] strKey) { if (list != null && list.size() > 0) {// 如果list有值 List<String[]> strList = new ArrayList<String[]>();// 實(shí)例化一個(gè)list<string[]> for (Map<String, Object> map : list) {// 遍歷數(shù)組 String[] str = new String[strKey.length];// 實(shí)力一個(gè)string[] Integer count = 0;// 作為str的下標(biāo),每次從0開(kāi)始 for (String s : strKey) {// 遍歷map中的key if (map.get(s) != null) { str[count] = map.get(s).toString(); } else { str[count] = ""; } // 把map的value賦值到str數(shù)組中 count++;// str的下標(biāo)+1 } if (str != null) {// 如果str有值,添加到strList strList.add(str); } } if (strList != null && strList.size() > 0) {// 如果strList有值,返回strList return strList; } } return null; } /** * @Description: 導(dǎo)出對(duì)象 * * @Author: 楊永卓 * @Date: 2022/9/5 10:34 */ private static class ExcelExp { private String fileName;// sheet的名稱(chēng) private String[] handers;// sheet里的標(biāo)題 private List<String[]> dataset;// sheet里的數(shù)據(jù)集 private String tableName; public ExcelExp(String fileName, String[] handers, List<String[]> dataset, String tableName) { this.fileName = fileName; this.handers = handers; this.dataset = dataset; this.tableName = tableName; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String[] getHanders() { return handers; } public void setHanders(String[] handers) { this.handers = handers; } public List<String[]> getDataset() { return dataset; } public void setDataset(List<String[]> dataset) { this.dataset = dataset; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } } }
以上就是Java實(shí)現(xiàn)多個(gè)sheet頁(yè)數(shù)據(jù)導(dǎo)出功能的詳細(xì)內(nèi)容,更多關(guān)于Java多個(gè)sheet數(shù)據(jù)導(dǎo)出的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
jenkins+Maven從SVN上構(gòu)建項(xiàng)目的方法
這篇文章主要介紹了jenkins+Maven從SVN上構(gòu)建項(xiàng)目,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-09-09Idea2023配置JavaWeb項(xiàng)目(最新)
本文將介紹如何配置JavaWeb項(xiàng)目,以在Idea中實(shí)現(xiàn)開(kāi)發(fā)環(huán)境,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09WebSocket實(shí)現(xiàn)數(shù)據(jù)庫(kù)更新時(shí)前端頁(yè)面刷新
這篇文章主要為大家詳細(xì)介紹了WebSocket實(shí)現(xiàn)數(shù)據(jù)庫(kù)更新時(shí)前端頁(yè)面刷新,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04springboot使用yml文件配置多環(huán)境方式(dev、test、prod)
這篇文章主要介紹了springboot使用yml文件配置多環(huán)境方式(dev、test、prod),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09