2.excel导出-poi使用
生活随笔
收集整理的這篇文章主要介紹了
2.excel导出-poi使用
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
POI
1 POI概述
1 什么是poi
? Apache POI是Apache軟件基金會(huì)的開放源碼函式庫(kù),POI提供API給Java程序?qū)icrosoft Office格式檔案讀和寫的功能。
2 包結(jié)構(gòu)說明
- HSSF提供讀寫Microsoft Excel XLS格式檔案的功能。
- XSSF提供讀寫Microsoft Excel OOXML XLSX格式檔案的功能。
- HWPF提供讀寫Microsoft Word DOC格式檔案的功能。
- HSLF提供讀寫Microsoft PowerPoint格式檔案的功能。
- HDGF提供讀Microsoft Visio格式檔案的功能。
- HPBF提供讀Microsoft Publisher格式檔案的功能。
- HSMF提供讀Microsoft Outlook格式檔案的功能。
2 POI的使用
2.1 Excel的操作
2.2.1 jar包依賴
導(dǎo)入jar包–本次使用maven,所以導(dǎo)入pom依賴。
<dependencies><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.8</version></dependency><dependency><groupId>org.apache.xmlbeans</groupId><artifactId>xmlbeans</artifactId><version>3.1.0</version></dependency><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency><dependency><groupId>poi</groupId><artifactId>poi-scratchpad-2.5.1-final</artifactId><version>20040804</version></dependency> </dependencies>2.2.2 Excel文件的導(dǎo)出
public static void writerExcel() throws IOException {ArrayList<Student> students = new ArrayList<>();for (int i = 0; i < 5; i++) {students.add(new Student(i+1000,"張三"+i,"男",60+Float.parseFloat(""+Math.random()*40)));}//1.創(chuàng)建excel對(duì)象HSSFWorkbook sheets = new HSSFWorkbook();//2.創(chuàng)建一個(gè)sheetHSSFSheet sheet1 = sheets.createSheet("sheet1");//4.創(chuàng)建行列并賦值:下標(biāo)默認(rèn)從0開始HSSFRow row = sheet1.createRow(0);//3.設(shè)置樣式HSSFCellStyle style = sheets.createCellStyle();style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);//設(shè)置圖案顏色style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//設(shè)置圖案樣式String[] rows=new String[]{"序號(hào)","學(xué)號(hào)","名字","性別","成績(jī)"};for (int i = 0; i < rows.length; i++) {//HSSFCell cell = row.createCell(i);Cell cell = row.createCell(i);cell.setCellValue(rows[i]);cell.setCellStyle(style);System.out.println(cell.getCellStyle().getFillBackgroundColor());}for (int i = 0; i < students.size(); i++) {HSSFRow tempRow = sheet1.createRow(i+1);Student tempStudent = students.get(i);HSSFCell cell = tempRow.createCell(0);cell.setCellValue(i+1);tempRow.createCell(1).setCellValue(tempStudent.getId());tempRow.createCell(2).setCellValue(tempStudent.getName());tempRow.createCell(3).setCellValue(tempStudent.getSex());tempRow.createCell(4).setCellValue(tempStudent.getScore());}//5.創(chuàng)建關(guān)聯(lián)輸出流和文件FileOutputStream fileOutputStream = new FileOutputStream("14_poi/studentScoreBook.xls");sheets.write(fileOutputStream);fileOutputStream.close(); }2.2.3 EXCEL文件的讀
public static void readExcel() throws IOException {//創(chuàng)建文件輸入流關(guān)聯(lián)表FileInputStream fileInputStream = new FileInputStream("14_poi/studentScoreBook.xls");//1.創(chuàng)建工作簿HSSFWorkbook sheets = new HSSFWorkbook(fileInputStream);//2.獲取工作表int numberOfSheets = sheets.getNumberOfSheets();//3.獲取每一個(gè)單元格for (int i = 0; i < numberOfSheets; i++) {HSSFSheet sheetAt = sheets.getSheetAt(i);Iterator<Row> rowIterator = sheetAt.iterator();while (rowIterator.hasNext()){//獲取一行Row rowNext = rowIterator.next();Iterator<Cell> cellIterator = rowNext.cellIterator();while (cellIterator.hasNext()){//獲取每一個(gè)單元格Cell cellNext = cellIterator.next();int cellType = cellNext.getCellType();if (cellType== HSSFCell.CELL_TYPE_NUMERIC){//日期和數(shù)字類型的if (HSSFDateUtil.isCellDateFormatted(cellNext)){Date dateCellValue = cellNext.getDateCellValue();System.out.println(dateCellValue);}else {double numericCellValue = cellNext.getNumericCellValue();System.out.println("numeric::"+numericCellValue);}}else if (cellType==HSSFCell.CELL_TYPE_BOOLEAN){boolean booleanCellValue = cellNext.getBooleanCellValue();System.out.println("boolean::"+booleanCellValue);}else{String stringCellValue = cellNext.getStringCellValue();System.out.println("其他類型使用字符串進(jìn)行接收::"+stringCellValue);}}}fileInputStream.close();} }2.2.4 文件的上傳與下載
? 需求:上傳一個(gè)文件并保存到本地磁盤中去。
@RequestMapping("/extractAllStudentToExcel") public ResponseEntity<byte[]> extractAllStudentToExcel(HttpServletRequest request) {//1.獲取全部的學(xué)生對(duì)象List<Student> allStudent = studentDao.getAllStudent();allStudent.forEach(System.out::println);//2.創(chuàng)建工作表HSSFWorkbook sheets = new HSSFWorkbook();HSSFSheet sheet = sheets.createSheet("學(xué)生信息表");//4.創(chuàng)建行列并賦值:下標(biāo)默認(rèn)從0開始HSSFRow row = sheet.createRow(0);//3.設(shè)置樣式String[] rows=new String[]{"序號(hào)","學(xué)號(hào)","名字","性別","成績(jī)","入學(xué)時(shí)間"};System.out.println(HSSFWorkbook.class.getProtectionDomain().getCodeSource().getLocation());for (int i = 0; i < rows.length; i++) {Cell cell = row.createCell(i);cell.setCellValue(rows[i]);}for (int i = 0; i < allStudent.size(); i++) {HSSFRow tempRow = sheet.createRow(i+1);Student tempStudent = allStudent.get(i);HSSFCell cell = tempRow.createCell(0);cell.setCellValue(i+1);tempRow.createCell(1).setCellValue(tempStudent.getId());tempRow.createCell(2).setCellValue(tempStudent.getName());tempRow.createCell(3).setCellValue(tempStudent.getSex());tempRow.createCell(4).setCellValue(tempStudent.getScore());Cell dateTemp=tempRow.createCell(5);HSSFCellStyle style4 = sheets.createCellStyle();HSSFDataFormat df = sheets.createDataFormat(); // 此處設(shè)置數(shù)據(jù)格式style4.setDataFormat(df.getFormat("yyyy-MM-dd hh:mm:ss"));dateTemp.setCellValue(tempStudent.getBirth());dateTemp.setCellStyle(style4);}//5.創(chuàng)建關(guān)聯(lián)輸出流和文件String fileName="學(xué)生信息.xls";String mimeType = request.getServletContext().getMimeType(fileName);MultiValueMap<String,String> headers=new HttpHeaders();headers.add("Content-Disposition","attchement;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));System.out.println("mmeType:"+mimeType);headers.add("Content-Type", mimeType);byte[] bytes = sheets.getBytes();System.out.println(bytes);return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } @RequestMapping("/saveStudentByExcel") public String saveStudentByExcel(@RequestParam(value = "file",required = false)MultipartFile file) throws IOException {if (!file.isEmpty()){InputStream inputStream = file.getInputStream();//1.創(chuàng)建工作簿HSSFWorkbook sheets = new HSSFWorkbook(inputStream);//2.獲取工作表Sheet sheet = sheets.getSheetAt(0);//獲取一個(gè)工作表for (int k = 1; k < sheet.getPhysicalNumberOfRows(); k++) {Row row = sheet.getRow(k);//獲取一行數(shù)據(jù)//獲取行下的所有單元格Student s = new Student();for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {Cell cell = row.getCell(j);//獲取下標(biāo)為j的單元格//判斷單元格數(shù)據(jù)的類型if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {String value = cell.getStringCellValue();if (j==2){s.setName(value);}else if(j==3){s.setSex(value);}} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {//數(shù)字和日期類型//判斷單元格數(shù)據(jù)的格式if (HSSFDateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時(shí)間格式Date value = cell.getDateCellValue();s.setBirth(value);} else {double value = cell.getNumericCellValue();if (j == 1) {s.setId((int) value);}if (j == 4) {s.setScore((float) value);}}}}studentDao.addOne(s);}}return "success"; }2.2 單元格的樣式設(shè)置
? HSSFCellStyle cellStyle = wb.createCellStyle();
2.3.1 設(shè)置背景色
cellStyle.setFillForegroundColor((short) 13);// 設(shè)置背景色 cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);2.3.2 設(shè)置邊框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下邊框 cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左邊框 cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上邊框 cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右邊框2.3.3 設(shè)置居中:
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中2.3.4 設(shè)置字體:
HSSFFont font = wb.createFont(); font.setFontName("黑體"); font.setFontHeightInPoints((short) 16);//設(shè)置字體大小 HSSFFont font2 = wb.createFont(); font2.setFontName("仿宋_GB2312"); font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗體顯示 font2.setFontHeightInPoints((short) 12); cellStyle.setFont(font);//選擇需要用到的字體格式2.3.5 設(shè)置列寬:
sheet.setColumnWidth(0, 3766); //第一個(gè)參數(shù)代表列id(從0開始),第2個(gè)參數(shù)代表寬度值 參考 :"2012-08-10"的寬度為25002.3.6 設(shè)置自動(dòng)換行:
cellStyle.setWrapText(true);//設(shè)置自動(dòng)換行2.3.7 合并單元格:
Region region1 = new Region(0, (short) 0, 0, (short) 6);//參數(shù)1:行號(hào) 參數(shù)2:起始列號(hào) 參數(shù)3:行號(hào) 參數(shù)4:終止列號(hào) //此方法在POI3.8中已經(jīng)被廢棄,建議使用下面一個(gè) 或者用 CellRangeAddress region1 = new CellRangeAddress(rowNumber, rowNumber, (short) 0, (short) 11); //參數(shù)1:起始行 參數(shù)2:終止行 參數(shù)3:起始列 參數(shù)4:終止列 但應(yīng)注意兩個(gè)構(gòu)造方法的參數(shù)不是一樣的,具體使用哪個(gè)取決于POI的不同版本。 sheet.addMergedRegion(region1);總結(jié)
以上是生活随笔為你收集整理的2.excel导出-poi使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: arduino nano 简单实现蓝牙模
- 下一篇: C的圆柱计算器