자바 엑셀 내 보 내기 기능 구현

18740 단어 자바도 출Excel
엑셀 을 내 보 내 는 것 은 우리 자바 가 개발 한 필수 기능 입 니 다.이전 프로젝트 에 이런 기능 이 있 었 는데 지금 은 독립 적 으로 공유 하 겠 습 니 다.
사용 하 는 기술 은 바로 SpringBoot 이 고 그 다음은 MVC 구조 모델 이다.
쓸데없는 말 은 그만 하고 코드 를 바로 올 리 면 소스 코드 끝 링크 를 다운로드 할 수 있 습 니 다.
(1)SpringBoot 프로젝트 새로 만 들 기(홈 페이지 가능)https://start.spring.io/직접 다운로드 생 성 후 eclipse 가 져 오기)프로젝트 구 조 는 다음 과 같 습 니 다.
(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>

 <!--   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)사용자.자바 라 는 실체 클래스 를 새로 만 듭 니 다.

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; //    
 private String address; //   
 private String hobby; //   
 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)엑셀 스타일 도구 류 를 새로 만 듭 니 다.

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 {
 /**
 *        
 * @param workbook
 * @return
 */
 public static CellStyle headSytle(SXSSFWorkbook workbook){
 //   style1   ,         
 CellStyle style1 = workbook.createCellStyle();// cell  
 //         ,                  
 style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//       
 style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);//      
 //       、 、 、     
 style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
 style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
 style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
 Font font1 = workbook.createFont();//         
 font1.setBoldweight((short) 10);//        
 font1.setFontHeightInPoints((short) 10);//        
 font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//     
 style1.setFont(font1);//   style1   
 style1.setWrapText(true);//       
 style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);//            (    )
 style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//            (    )
 return style1;
 }
 /**
 *        
 * @param wb
 * @return
 */
 public static CellStyle contentStyle(SXSSFWorkbook wb){
 //   style1   ,         
 CellStyle style1 = wb.createCellStyle();// cell  
 //       、 、 、     
 style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
 style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
 style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
 style1.setWrapText(true);//       
 style1.setAlignment(HSSFCellStyle.ALIGN_LEFT);//            (    )
 style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//            (    )
 return style1;
 }
 /**
 *         
 * @param workbook
 * @return
 */
 public static HSSFCellStyle titleSytle(HSSFWorkbook workbook,short color,short fontSize){
 //   style1   ,         
 HSSFCellStyle style1 = workbook.createCellStyle();// cell  
 //         ,                  
 //style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//       
 //short fcolor = color;
 if(color != HSSFColor.WHITE.index){
 style1.setFillForegroundColor(color);//       
 }
 //       、 、 、     
 style1.setBorderBottom(HSSFCellStyle.BORDER_THIN);
 style1.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 style1.setBorderRight(HSSFCellStyle.BORDER_THIN);
 style1.setBorderTop(HSSFCellStyle.BORDER_THIN);
 HSSFFont font1 = workbook.createFont();//         
 font1.setBoldweight(fontSize);//        
 font1.setFontHeightInPoints(fontSize);//        
 font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//     
 style1.setFont(font1);//   style1   
 style1.setWrapText(true);//       
 style1.setAlignment(HSSFCellStyle.ALIGN_CENTER);//            (    )
 style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//            (    )
 return style1;
 }
 /**
 *     
 * @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);
 //         
 cell.setCellValue(title[j]);
 cell.setCellStyle(header);
 sheet.setColumnWidth(j, titleLength[j]);
 }
 }
}
(5)서비스 인 터 페 이 스 를 새로 만 듭 니 다.

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)서비스 인터페이스 구현 클래스 를 새로 만 듭 니 다.

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(">>>>>>>>>>    excel>>>>>>>>>>");
 
 //      
 List<User> list = new ArrayList<>();
 list.add(new User("   ", " ", 30, "13411111111", "    ", "   "));
 list.add(new User("   ", " ", 29, "13411111112", "   ", "   "));
 list.add(new User("   ", " ", 28, "13411111113", "   ", "  "));
 list.add(new User("   ", " ", 27, "13411111114", "   ", "   "));
 
 BaseFrontController baseFrontController = new BaseFrontController();
 return baseFrontController.buildResponseEntity(export((List<User>) list), "   .xls");
 } catch (Exception e) {
 e.printStackTrace();
 logger.error(">>>>>>>>>>  excel   ,   :" + e.getMessage());
 }
 return null;
 }

 private InputStream export(List<User> list) {
 logger.info(">>>>>>>>>>>>>>>>>>>>        >>>>>>>>>>");
 ByteArrayOutputStream output = null;
 InputStream inputStream1 = null;
 SXSSFWorkbook wb = new SXSSFWorkbook(1000);//   1000       
 SXSSFSheet sheet = wb.createSheet();
 //        
 CellStyle header = ExcelFormatUtil.headSytle(wb);// cell  
 CellStyle content = ExcelFormatUtil.contentStyle(wb);//      
 
 //       
 String[] strs = new String[] { "  ", "  ", "  ", "   ", "  ","  " };
 
 //           
 int[] ints = new int[] { 5000, 5000, 5000, 5000, 5000, 5000 };
 
 //       
 ExcelFormatUtil.initTitleEX(sheet, header, strs, ints);
 logger.info(">>>>>>>>>>>>>>>>>>>>        >>>>>>>>>>");
 
 if (list != null && list.size() > 0) {
 logger.info(">>>>>>>>>>>>>>>>>>>>             >>>>>>>>>>");
 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()); //    
 cell.setCellStyle(content);

 cell = row.createCell(j++);
 cell.setCellValue(user.getAddress()); //   
 cell.setCellStyle(content);
 
 cell = row.createCell(j++);
 cell.setCellValue(user.getHobby()); //   
 cell.setCellStyle(content);
 }
 logger.info(">>>>>>>>>>>>>>>>>>>>             >>>>>>>>>>");
 }
 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)파일 을 다운로드 하 는 유 니 버 설 컨트롤 러 를 새로 만 듭 니 다.

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   
 *
 * @param is      
 * @param name     ,    
 *
 * @throws Exception
 */
 public ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception {
 logger.info(">>>>>>>>>>>>>>>>>>>>      >>>>>>>>>>");
 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(">>>>>>>>>>>>>>>>>>>>      -   >>>>>>>>>>");
 logger.info(">>>>>>>>>>    excel>>>>>>>>>>");
 return new ResponseEntity<>(bs, header, HttpStatus.OK);
 }else{
 String string="    ";
 header.add("Content-Length", "0");
 header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
 logger.info(">>>>>>>>>>>>>>>>>>>>      -   >>>>>>>>>>");
 logger.info(">>>>>>>>>>    excel>>>>>>>>>>");
 return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);
 }
 }
}
(8)요청 한 입구 로 controller 를 새로 만 듭 니 다.

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;

 //   excel
 @RequestMapping("exportExcel")
 public ResponseEntity<byte[]> exportExcel(HttpServletRequest request, HttpServletResponse response) {
 return exportService.exportExcel(request,response);
 }
}
(9)ExportExcel 응용 프로그램 실행,브 라 우 저 접근http://localhost:8080/exportExcel/exportExcel,엑셀 을 다운로드 할 수 있 습 니 다.다음 과 같이 열 수 있 습 니 다.

(10) 프로젝트 원본 코드
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기