java集成poi框架

介紹 : Apache POI是Apache軟件基金會的開放源碼函式庫,POI提供API給Java程序對Microsoft Office格式檔案讀和寫的功能。

下面簡單介紹一下如何使用該框架:

一:導入依賴

 <!--        excel解析依賴--><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>${org.poi-version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>${org.poi-version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-examples</artifactId><version>${org.poi-version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-excelant</artifactId><version>${org.poi-version}</version></dependency><!-- https://mvnrepository.com/artifact/com.monitorjbl/xlsx-streamer --><dependency><groupId>com.monitorjbl</groupId><artifactId>xlsx-streamer</artifactId><version>2.1.0</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency><!--阿里巴巴EasyExcel依賴--><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.0.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>${hutool.version}</version></dependency><!--        <dependency>--><!--            <groupId>org.projectlombok</groupId>--><!--            <artifactId>lombok</artifactId>--><!--        </dependency>--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.hynnet</groupId><artifactId>jxl</artifactId><version>2.6.12.1</version></dependency><!-- https://mvnrepository.com/artifact/com.bulucat/BeautyEye --><dependency><groupId>com.bulucat</groupId><artifactId>BeautyEye</artifactId><version>1.0.0</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.21</version></dependency><dependency><groupId>javax.annotation</groupId><artifactId>javax.annotation-api</artifactId><version>1.3.2</version></dependency>

二:創建實體類及dao層(查詢得到結果集封裝在list中即可,此處不做過多贅述)

三:在serviceImpl中處理結果集

 @AutowiredDbToExcelDao dbToExcelDao;@Overridepublic List<String[]> getAllCity(QueryDto dto) {List<CityInfo> cityInfoList = dbToExcelDao.getAllCity(dto);List<String[]> result=new ArrayList<>();for (CityInfo cityInfo : cityInfoList) {String[] cityInfoArr = new String[7];//將查詢到的結果集轉換成字符串存入字符串數組中cityInfoArr[0] = xxx;cityInfoArr[1] = xxx;cityInfoArr[2] = xxx;cityInfoArr[3] = xxx;cityInfoArr[4] = xxx;//將該字符串數組存入list中result.add(cityInfoArr);}return result;}

四:在controller中調用service對象使用poi工具類導出表格。

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;/***** 文件導入導出工具類***/
public class ExcelUtils {/*** 導出excel文件的方法** @param titles 輸出到excel的表頭* @param datas  數據庫的表中的數據 集合對象* @param out excel(File) 輸出到指定的路徑 (OutPutStream)*/public static void export(List<String[]> titles, List<List<String[]>> datas, OutputStream out) {// 創建工作表HSSFWorkbook work = new HSSFWorkbook();for (int k = 0;k<datas.size();k++){String sheetname = "";// 創建sheet表if(k == 0){if(datas.size() > 1){sheetname = "xxx";//sheet名}else {sheetname = "xxx";//sheet名}}else if(k == 1){sheetname = "xxx";//sheet名}else if(k == 2){sheetname = "xxx";//sheet名}HSSFSheet sheet = work.createSheet(sheetname);// 創建表頭【表頭數據來源】Row headRow = sheet.createRow(0);// 循環輸出標題for (int i = 0; i < titles.get(k).length; i++) {// 設置字體HSSFCellStyle redStyle = work.createCellStyle();
//           CellStyle redStyle = work.createCellStyle();HSSFFont redFont = work.createFont();//字體顏色redFont.setColor((short) 9);//設置字體大小redFont.setFontHeightInPoints((short) 10);//字體樣式redFont.setFontName("Microsoft YaHei");//加粗redFont.setBold(true);redStyle.setFont(redFont);//設置居中redStyle.setAlignment(HorizontalAlignment.CENTER);redStyle.setVerticalAlignment(VerticalAlignment.CENTER);//背景色redStyle.setFillForegroundColor(IndexedColors.BLACK.getIndex());redStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 上薄邊框redStyle.setBorderTop(BorderStyle.THIN);// 下薄邊框redStyle.setBorderBottom(BorderStyle.THIN);// 左薄邊框redStyle.setBorderLeft(BorderStyle.THIN);// 右薄邊框redStyle.setBorderRight(BorderStyle.THIN);// 下邊框:黑色redStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 右邊框:黑色redStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 左邊框:黑色redStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 上邊框:黑色redStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());//創建cell,嵌入樣式Cell cell = headRow.createCell(i);cell.setCellStyle(redStyle);cell.setCellValue(titles.get(k)[i]); // 設置cell中的內容}// 表體內容// 設置表體內容 嵌套循環for (int row = 0; row < datas.get(k).size(); row++) {// 創建行HSSFRow sheetRow = sheet.createRow(row + 1);// 循環 創建列for (int c = 0; c < datas.get(k).get(row).length; c++) {sheet.autoSizeColumn(c, true);// 設置字體HSSFCellStyle redStyle = work.createCellStyle();
//           CellStyle redStyle = work.createCellStyle();HSSFFont redFont = work.createFont();//字體顏色redFont.setColor((short) 8);//設置字體大小redFont.setFontHeightInPoints((short) 10);//字體樣式redFont.setFontName("等線");//加粗
//                redFont.setBold(true);redStyle.setFont(redFont);//設置居中redStyle.setAlignment(HorizontalAlignment.CENTER);redStyle.setVerticalAlignment(VerticalAlignment.CENTER);//背景色
//                redStyle.setFillForegroundColor(IndexedColors.BLACK.getIndex());
//                redStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 上薄邊框redStyle.setBorderTop(BorderStyle.THIN);// 下薄邊框
//                    if(row == datas.size()){redStyle.setBorderBottom(BorderStyle.THIN);
//                    }// 左薄邊框redStyle.setBorderLeft(BorderStyle.THIN);// 右薄邊框
//                    if(c == datas.get(k).get(row).length-1){redStyle.setBorderRight(BorderStyle.THIN);
//                    }// 下邊框:黑色redStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 右邊框:黑色redStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 左邊框:黑色redStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());// 上邊框:黑色redStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());HSSFCell sheetCell = sheetRow.createCell(c);sheetCell.setCellStyle(redStyle);// 設置內容sheetCell.setCellValue(datas.get(k).get(row)[c]);}}}// 創建完成后,內存創建的Excel輸出到文件中try {work.write(out);out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}/***  導入excel文件的方法**  suffix: 傳入excel的后綴名*      excel  2003版的后綴為(xls) HSSFWorkbook  2007版的后綴為(xlsx)XSSFWorkbook*  fis :   通過輸入流來讀取excel的內容*  startRow: 讀取內容的起始行**  @return 返回導入的數據    List<String[]>**/public static List<String[]> importData(MultipartFile file, int startrow) {List<String[]> datas = new ArrayList<String[]>();// 創建表格對象Workbook work = null;try {//獲取文件流對象InputStream fis = file.getInputStream();//獲取文件的后綴String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));// 判斷后綴名if (suffix.equals(".xls")) {work = new HSSFWorkbook(fis); // 2003的工作表對象} else if (suffix.equals(".xlsx")) { //work = new XSSFWorkbook(fis); // 2007的工作表對象} else {return null;}} catch (IOException e) {e.printStackTrace();}// 獲取sheet表格Sheet sheet = work.getSheetAt(0);if (sheet == null) { // 代表一個sheet表格也沒有return null;}// 獲取一共多少行int rownum = sheet.getLastRowNum();if (rownum == 0 || rownum+1 == startrow) {return null;}for (int i = startrow; i <= rownum; i++) {// 獲取行Row row = sheet.getRow(i);// 獲取列short first = row.getFirstCellNum(); //起始列的下標short num = row.getLastCellNum();    //終止列的下標String[] cols = new String[num];    //存放當前行所有的列內容for (int j = first; j < num; j++) {// 處理列對象Cell cell = row.getCell(j);
//                if(j == 10){
//                    String[] dates = row.getCell(7).toString().split("-");
//                    String year = dates[2];
//                    String  month = dates[1].substring(0,dates[1].length()-1);
//                    //獲取年份差
//                    int yx = Integer.parseInt(row.getCell(1).toString().substring(0,4) )- Integer.parseInt(year);
//                    //獲取月份差
//                    int mx = Integer.parseInt(row.getCell(1).toString().substring(4,6)) - Integer.parseInt(month);
//                    cols[j] = yx*12+mx+1 + "";
//                    continue;
//                }//獲取指定列的內容, 都轉換為String類型cols[j] = parseCell(cell);}datas.add(cols);  //列處理完成以后,把該行所有列添加集合中}return datas;}// 轉換類型private static String parseCell(Cell cell) {String cellValue = "";if(cell == null){return null;}//判斷如果是String類型 則去除空格if (cell.getCellTypeEnum() == CellType.STRING) {cellValue = cell.getStringCellValue().trim();} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) { //如果是boolean類型則獲取boolean類型的值cellValue = String.valueOf(cell.getBooleanCellValue());} else if (cell.getCellTypeEnum() == CellType.NUMERIC) { //如果是數字類型, 則判斷是日期類型還是普通數字if (HSSFDateUtil.isCellDateFormatted(cell)) { // 判斷日期類型double d = cell.getNumericCellValue();Date date = HSSFDateUtil.getJavaDate(d);cellValue = new SimpleDateFormat("yyyy-MM-dd").format(date);} else { // 否cellValue = new DecimalFormat("#.######").format(cell.getNumericCellValue());}} else {cellValue = "";}return cellValue;}//圖片處理public static List<String> savePic(InputStream fis) throws Exception {HSSFWorkbook workbook = (HSSFWorkbook) WorkbookFactory.create(fis);List<HSSFPictureData> pictures = workbook.getAllPictures();HSSFSheet sheet = workbook.getSheetAt(0);List<String> picList = new ArrayList<>();for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();if (shape instanceof HSSFPicture) {HSSFPicture pic = (HSSFPicture) shape;int row = anchor.getRow1();int pictureIndex = pic.getPictureIndex() - 1;HSSFPictureData picData = pictures.get(pictureIndex);//獲取文件后綴String ext = picData.suggestFileExtension();//獲取圖片內容byte[] data = picData.getData();//通過文件流將圖片寫入到指定的位置String filename = UUID.randomUUID().toString().replace("-", "");FileOutputStream out = new FileOutputStream("D:\\upload\\"+ filename +"."+ext);out.write(data);out.close();picList.add(filename+"."+ext);}}return picList;}
}
    @AutowiredDbToExcelService dbToExcelService;//導出結果表@RequestMapping("export")public void exportFileReconnect(HttpServletResponse res,QueryDto querydto) throws IOException {//定義添加標題String[] title1={"xx","xx","xx","xx","xx"};List<String[]> title = new ArrayList<>();title.add(title1);//定義添加內容,也可以存入多個list,作一個表中的不同sheetList<String[]> list1 = dbToExcelService.getAllReconnect(querydto);List<List<String[]>> list = new LinkedList<>();list.add(list1);//設置響應頭,告知瀏覽器是下載操作res.setHeader("Content-Disposition","attachment;filename=futongtongji.xls");//設置MIME類型res.setContentType("application/vnd.ms-excel");//這里要傳遞的字節流數據,excel為字節流文件ExcelUtils.export(title,list,res.getOutputStream());}@AutowiredExcelToDbService excelToDbService;//文件導入數據庫@RequestMapping("import")@ResponseBodypublic ResultData importFile(MultipartFile file) throws Exception {//獲取excel的數據List<String[]> list = ExcelUtils.importData(file, 1);//獲取excel中圖片的數據List<String> strings = ExcelUtils.savePic(file.getInputStream());for (int i = 0; i < list.size(); i++) {//將圖片數據渲染到excel表格中list.get(i)[1]= strings.get(i);}//上傳數據就是一個增加的過程ResultData resultData = excelToDbService.insertAll(list);return resultData;}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/167081.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/167081.shtml
英文地址,請注明出處:http://en.pswp.cn/news/167081.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

17 redis集群方案

1、RedisCluster分布式集群解決方案 為了解決單機內存&#xff0c;并發等瓶頸&#xff0c;可使用此方案解決問題. Redis-cluster是一種服務器Sharding技術&#xff0c;Redis3.0以后版本正式提供支持。 這里的集群是指多主多從&#xff0c;不是一主多從。 2、redis集群的目標…

pair和typedef

文章目錄 一、pair用法1.2、pair的創建和初始化1.3、pair對象的操作1.4、(make_pair)生成新的pair對象1.5、通過tie獲取pair元素值 2、typedef2.1、什么是typedef2.2、typedef用法2.2.1、對于數據類型使用例如&#xff1a;2.2.2、對于指針的使用例如2.2.3、對于結構體的使用 2.…

java springboot測試類虛擬MVC環境 匹配返回值與預期內容是否相同 (JSON數據格式) 版

上文java springboot測試類鑒定虛擬MVC請求 返回內容與預期值是否相同我們講了測試類中 虛擬MVC發送請求 匹配返回內容是否與預期值相同 但是 讓我意外的是 既然沒人罵我 因為我們實際開發 返回的基本都是json數據 字符串的接口場景是少數的 我們在java文件目錄下創建一個 dom…

2023年10月紙巾市場分析(京東天貓淘寶平臺紙巾品類數據采集)

雙十一大促期間&#xff0c;剛需品的紙巾是必囤商品之一。今年雙十一&#xff0c;京東數據顯示&#xff0c;10月23日至29日&#xff0c;清潔紙品成交額同比增長40%&#xff0c;由此也拉動了10月紙巾市場的銷售。 鯨參謀數據顯示&#xff0c;今年10月&#xff0c;京東平臺紙巾市…

【日常總結】如何禁止瀏覽器 http自動跳轉成https

一、場景 二、問題 三、解決方案 3.1 chrome 瀏覽器 3.2 edge 瀏覽器&#xff1a; 3.3 Safari 瀏覽器 3.4 Firefox 瀏覽器 3.5 Microsoft Edge 一、場景 公司網站 http:// 谷歌瀏覽器中自動轉換成 https:// 導致無法訪問 二、問題 nginx配置ssl 443接口&#xff0c; ht…

SOLIDWORKS 2024新功能之Electrical篇

SOLIDWORKS 2024 Electrical篇目錄概覽 ? 對齊零部件 ? 更改多個導軌和線槽的長度 ? 過濾輔助和附件零件 ? 2D 機柜中的自動零件序號 ? 移除制造商零件數據 ? 重置未定義的宏變量 ? 使用范圍縮短列表 ? SOLIDWORKS Electrical Schematic 增強功能 1、對齊零部件…

ONNX實踐系列-修改yolov5-seg的proto分支輸出shape

一、目標 本文主要介紹要將原始yolov5分割的輸出掩膜從[b,c,h,.w]修改為[b, h, w, c] 原來的: 目標的: 代碼如下: Descripttion: version: @Company: WT-XM Author: yang jinyi Date: 2023-09-08 11:26:28 LastEditors: yang jinyi LastEditTime: 2023-09-08 11:48:01 …

Threejs_14 制作圣誕賀卡

繼續跟著老陳打碼學習&#xff01;&#xff01;&#xff01;支持&#xff01;&#xff01;&#xff01; 效果圖 鏈接&#xff1a;https://pan.baidu.com/s/1Ft8U2HTeqmpyAeesL31iUg 提取碼&#xff1a;6666 使用到的 模型文件和資源等都為老陳打碼提供&#xff01;&#x…

【騰訊云云上實驗室】探索保護數據之盾背后的安全監控機制

當今數字化時代&#xff0c;數據安全成為了企業和個人最為關注的重要議題之一。隨著數據規模的不斷增長和數據應用的廣泛普及&#xff0c;如何保護數據的安全性和隱私性成為了迫切的需求。 今天&#xff0c;我將帶領大家一起探索騰訊云云上實驗室所推出的向量數據庫&#xff0c…

新版PY系列離線燒錄器,支持PY002A/002B/003/030/071等MCU各封裝,不同 FLASH 大小型號

PY系列離線燒錄器&#xff0c;目前支持PY32F002A/002B/002/003/030/071/072/040/403/303 各封裝、不同 FLASH 大小型號。PY離線燒錄器需要搭配上位機軟件使用&#xff0c;上位機軟件可以在芯嶺技術官網上下載&#xff0c;還包括了離線燒錄器的使用說明。PY離線燒錄器使用MINI U…

金融機構如何高效率考勤?這個技巧幫了大忙!

在現代社會&#xff0c;隨著科技的不斷發展&#xff0c;人臉識別技術作為一種高效、便捷的身份驗證手段&#xff0c;逐漸應用于各個領域&#xff0c;其中之一便是人臉考勤系統。 傳統的考勤方式存在一系列問題&#xff0c;如卡片打卡容易被冒用、簽到表容易造假等&#xff0c;而…

CTFUB-web前置技能-HTTP協議

burp抓包,抓第二次的 修改請求方式為CTFHUB

算法筆記:OPTICS 聚類

1 基本介紹 OPTICS(Ordering points to identify the clustering structure)是一基于密度的聚類算法 OPTICS算法是DBSCAN的改進版本 在DBCSAN算法中需要輸入兩個參數&#xff1a; ? 和 MinPts &#xff0c;選擇不同的參數會導致最終聚類的結果千差萬別&#xff0c;因此DBCSAN…

線上PDF文件展示

場景&#xff1a; 請求到的PDF&#xff08;url鏈接&#xff09;&#xff0c;將其展示在頁面上 插件&#xff1a; pdfobject &#xff08;我使用的版本&#xff1a; "pdfobject": "^2.2.12" &#xff09; 下載插件就不多說了&#xff0c;下面將其引入&a…

【Clang Static Analyzer 代碼靜態檢測工具詳細使用教程】

Clang Static Analyzer sudo apt-get install clang-tools scan-build cmake .. scan-build make -j4 編譯完成之后會在終端提示在哪里查看報錯文檔: scan-build: 55 bugs found. scan-build: Run scan-view /tmp/scan-build-2023-11-24-150637-6472-1 to examine bug report…

Liunx Ubuntu Server 安裝配置 Docker

1. 安裝Docker 1.1 更新軟件包列表 sudo apt update1.2 添加Docker存儲庫 sudo apt install apt-transport-https ca-certificates curl gnupg-agent software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-a…

Django QuerySet.order_by SQL注入漏洞(CVE-2021-35042)

漏洞描述 Django 于 2021年7月1日發布了一個安全更新&#xff0c;修復了函數QuerySet.order_by中的 SQL 注入漏洞。 參考鏈接&#xff1a; Django security releases issued: 3.2.5 and 3.1.13 | Weblog | Django 該漏洞需要開發人員使用order_by功能。此外&#xff0c;還可…

加入華為云鯤鵬極簡開發創造營,激活創造力,探索無限可能!

數字經濟時代&#xff0c;速度、效率、質量安全已成為各行業告訴拓新發展的關鍵&#xff0c;華為云不斷打磨敏捷安全開發的軟件平臺&#xff0c;為更高效率的生產力變革積蓄能量。 在剛剛過去不久的2023華為全聯接大會上&#xff0c;華為最新發布了華為云CodeArts與鯤鵬DevKit…

關于配置文件中秘鑰信息加密實現方案的一些思考

關于配置文件中秘鑰信息加密實現方案的一些思考 背景實現方案 背景 配置信息文件中(代碼中), 不應該有明文的秘鑰信息. 需要找一種方案去做加密處理. 實現方案 我們可以在項目指定目錄上傳一份加密/解密程序, 例如: jasypt-gui.jar. 啟動時: 配置JVM參數, 對加密的信息進行解…

2023 Unite 大會關于“Muse“ AI 大模型訓練

Unity Muse 借助強大的 AI 能力幫助你探索、構思和迭代&#xff0c;其中包括紋理和精靈兩項功能&#xff0c;可將自然語言和視覺輸入轉化為可用資產。 將 AI 引入 Unity Editor 中的 Muse 提供了更快將想法轉化為實物的選項。您可以調整并使用文本提示、圖案、顏色和草圖&…