Java使用POI實(shí)現(xiàn)excel文件的導(dǎo)入和導(dǎo)出
說(shuō)明:
1、文件導(dǎo)出功能:
通過(guò)反射獲取實(shí)體類的屬性名和屬性值,寫(xiě)入文件是第一行為屬性名,從第二行開(kāi)始為屬性值,調(diào)用時(shí)只需傳入一個(gè)任意實(shí)體集合(List)即可。
2、文件導(dǎo)入功能
文件導(dǎo)入功能需要定義一個(gè)實(shí)體類用于接受解析excel后的內(nèi)容。
package com.cz.excel; import com.cz.model.TestCase; import org.apache.poi.hpsf.DocumentSummaryInformation; import org.apache.poi.hpsf.SummaryInformation; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.IndexedColors; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * 工具類,用于文件上傳、下載、解析 * @program: PostGirl-panent * @description: PoiUtils * @author: Cheng Zhi * @create: 2021-02-28 09:57 **/ public class PoiUtils { /** * 將對(duì)象集合導(dǎo)出到excel * @param list * @param <T> * @return */ public static <T> ResponseEntity<byte[]> exportToExcel(List<T> list) { // 1、創(chuàng)建一個(gè)excel文檔 HSSFWorkbook workbook = new HSSFWorkbook(); // 2、創(chuàng)建文檔摘要 workbook.createInformationProperties(); // 3、獲取并配置文檔摘要信息 DocumentSummaryInformation docInfo = workbook.getDocumentSummaryInformation(); // 文檔類別 docInfo.setCategory("文檔類別"); // 文檔管理員 docInfo.setManager("PostGirl"); // 設(shè)置公司信息 docInfo.setCompany("www.postgirl.com"); // 4、獲取文檔摘要信息 SummaryInformation summaryInformation = workbook.getSummaryInformation(); // 文檔標(biāo)題 summaryInformation.setTitle("文檔標(biāo)題"); // 文檔作者 summaryInformation.setAuthor("PostGirl"); // 備注信息 summaryInformation.setComments("本文檔由 PostGirl 提供"); // 5、創(chuàng)建樣式 // 創(chuàng)建標(biāo)題行的樣式 HSSFCellStyle headerStyle = workbook.createCellStyle(); headerStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); // 背景顏色 headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充模式 HSSFSheet sheet = workbook.createSheet();// 不傳name 默認(rèn)為sheet1 // 6、創(chuàng)建標(biāo)題行 第一行數(shù)據(jù) // 只循環(huán)一次目的是將對(duì)象名寫(xiě)入到excel標(biāo)題上 for (T t : list) { HSSFRow row = sheet.createRow(0); String[] fieldNames = getFiledNames(t); for (int i=0; i<fieldNames.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(fieldNames[i]); cell.setCellStyle(headerStyle); } break; } // 7、創(chuàng)建后面行 for (int j=0; j<list.size(); j++) { T t = list.get(j); String[] fieldValues = getFieldValues(t); // 由于第一行已經(jīng)寫(xiě)入了標(biāo)題,所以這里從第二行開(kāi)始寫(xiě) HSSFRow rows = sheet.createRow(j+1); for (int i=0; i<fieldValues.length; i++) { rows.createCell(i).setCellValue(fieldValues[i]); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); HttpHeaders headers = new HttpHeaders(); try { // 防止亂碼 headers.setContentDispositionFormData("attachment",new String("系統(tǒng)導(dǎo)出文件.xls".getBytes("UTF-8"),"ISO-8859-1")); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); workbook.write(baos); } catch (IOException e) { e.printStackTrace(); } return new ResponseEntity<byte[]>(baos.toByteArray(),headers, HttpStatus.CREATED); } /** * 傳入文件,解析并返回實(shí)體集合,用于后續(xù)操作 * @param file * @return */ public static List<TestCase> excelToEntity (MultipartFile file) { List<TestCase> list = new ArrayList<>(); TestCase testCase = null; try { // 1、創(chuàng)建一個(gè)workbook對(duì)象 HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream()); // 2、獲取workboot中表單的數(shù)量 int numberOfSheets = workbook.getNumberOfSheets(); for (int i=0; i<numberOfSheets; i++) { // 3、獲取sheet頁(yè) HSSFSheet sheet = workbook.getSheetAt(i); // 4、獲取sheet頁(yè)中的行數(shù) int physicalNumberOfRows = sheet.getPhysicalNumberOfRows(); for (int j=0; j<physicalNumberOfRows; j++) { if (j==0) { continue; // 跳過(guò)標(biāo)題行 } // 6、獲取行 HSSFRow row = sheet.getRow(j); if (row == null) { continue; // 防止數(shù)據(jù)中間有空行 } // 7、獲取列數(shù) int physicalNumberOfCells = row.getPhysicalNumberOfCells(); testCase = new TestCase(); testCase.setCreateDate(new Date()); testCase.setLastUpdateDate(new Date()); for (int k=0; k<physicalNumberOfCells; k++) { HSSFCell cell = row.getCell(k); switch (k) { case 1: testCase.setRequest(cell.getStringCellValue()); break; case 2: testCase.setExpectedResponse(cell.getStringCellValue()); break; case 5: testCase.setBusiCode(cell.getStringCellValue()); break; default: break; } } list.add(testCase); } } } catch (IOException e) { e.printStackTrace(); } return list; } /** * 獲取所有對(duì)象屬性名稱 * @param o * @return */ public static String[] getFiledNames(Object o) { Field[] fields=o.getClass().getDeclaredFields(); String[] fieldNames=new String[fields.length]; for(int i=0;i<fields.length;i++){ fieldNames[i]=fields[i].getName(); } return fieldNames; } /** * 獲取對(duì)象屬性值 * @param o * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ private static String[] getFieldValues(Object o) { Field[] fields=o.getClass().getDeclaredFields(); String[] fieldNames=new String[fields.length]; String[] fieldValues = new String[fieldNames.length]; for(int i=0;i<fields.length;i++){ fieldNames[i]=fields[i].getName(); } try { for (int i=0; i<fieldNames.length; i++) { String fieldName = fieldNames[i]; String field = o.getClass().getMethod("get" + returnFirstCapital(fieldName)).invoke(o).toString(); fieldValues[i] = field; } } catch(Exception e) { } return fieldValues; } /** * 判斷字符串首字母是否為大寫(xiě),如果不是轉(zhuǎn)化為大寫(xiě) * @param str * @return */ public static String returnFirstCapital(String str) { if (str.charAt(0) >= 'A' && str.charAt(0) <= 'Z') { return str; } char[] ch = str.toCharArray(); ch[0] -= 32; return String.valueOf(ch); } }
到此這篇關(guān)于Java使用POI實(shí)現(xiàn)excel文件的導(dǎo)入和導(dǎo)出的文章就介紹到這了,更多相關(guān)Java POI實(shí)現(xiàn)excel導(dǎo)入導(dǎo)出內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot3.2整合mybatis-plus詳細(xì)代碼示例
這篇文章主要給大家介紹了關(guān)于springboot3.2整合mybatis-plus的相關(guān)資料,Spring Boot是一個(gè)非常流行的Java Web框架,可以快速地搭建Web應(yīng)用程序,需要的朋友可以參考下2023-12-12從0開(kāi)始學(xué)習(xí)大數(shù)據(jù)之java spark編程入門(mén)與項(xiàng)目實(shí)踐
這篇文章主要介紹了從0開(kāi)始學(xué)習(xí)大數(shù)據(jù)之java spark編程入門(mén)與項(xiàng)目實(shí)踐,結(jié)合具體入門(mén)項(xiàng)目分析了大數(shù)據(jù)java spark編程項(xiàng)目建立、調(diào)試、輸出等相關(guān)步驟及操作技巧,需要的朋友可以參考下2019-11-11Java線程池submit阻塞獲取結(jié)果的實(shí)現(xiàn)原理詳解
Java線程池中提交任務(wù)運(yùn)行,通常使用execute()方法就足夠了。那如果想要實(shí)現(xiàn)在主線程中阻塞獲取線程池任務(wù)運(yùn)行的結(jié)果,該怎么辦呢?本文就來(lái)和大家一起討論討論2022-10-10Java在讀取文件內(nèi)容的時(shí)候,如何判斷出空白行的操作
這篇文章主要介紹了Java在讀取文件內(nèi)容的時(shí)候,如何判斷出空白行的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09Java實(shí)現(xiàn)模擬鍵盤(pán)鼠標(biāo)操作工具
在桌面自動(dòng)化、軟件測(cè)試、游戲開(kāi)發(fā)以及遠(yuǎn)程控制等領(lǐng)域中,模擬鍵盤(pán)和鼠標(biāo)操作是一項(xiàng)非常實(shí)用的技術(shù),本文將使用?Java?實(shí)現(xiàn)一個(gè)模擬鍵盤(pán)與鼠標(biāo)操作的工具,希望對(duì)大家有所幫助2025-03-03springboot restTemplate連接池整合方式
這篇文章主要介紹了springboot restTemplate連接池整合方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10