<
groupId
>
org
.
apache
.
poi
<
/
groupId
>
<
artifactId
>
poi
-
ooxml
<
/
artifactId
>
<
version
>
3.11
<
/
version
>
<
/
dependency
>
poi-ooxml是一个excel表格的操作工具包,处理的单页数据量也是百万级别的,因此我们选择的是poi-ooxml.
2.编写excel工具类
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class ExcelUtil {
* 用户信息导出类
* @param response 响应
* @param fileName 文件名
* @param columnList 每列的标题名
* @param dataList 导出的数据
public static void uploadExcelAboutUser(HttpServletResponse response,String fileName,List<String> columnList,<br>List<List<String>> dataList){
OutputStream os = null;
setResponseHeader(response,fileName);
try {
os = response.getOutputStream();
SXSSFWorkbook wb = new SXSSFWorkbook(1000);
Sheet sheet1 = wb.createSheet("sheet1");
int excelRow = 0;
Row titleRow = sheet1.createRow(excelRow++);
for(int i = 0;i<columnList.size();i++){
Cell cell = titleRow.createCell(i);
cell.setCellValue(columnList.get(i));
if(dataList!=null && dataList.size()>0){
int count = 1;
for(int i = 0;i<dataList.size();i++){
Row dataRow = sheet1.createRow(excelRow++);
for(int j = -1;j<dataList.get(0).size();j++){
Cell cell = dataRow.createCell(j+1);
if(j==-1){
cell.setCellValue(count++);
}else{
cell.setCellValue(dataList.get(i).get(j));
wb.write(os);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (os != null) {
os.close();
} catch (IOException e) {
e.printStackTrace();
设置浏览器下载响应头
private static void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
网上的excel的工具类有很多,但很多并不是你复制过来就能直接使用的,因此需要我们深究其原理,这样可以应对不同的场景写出属于我们自己的合适的代码,这里就不一一解释了,代码中注释加的很清楚,有不懂的可以留言评论。
3.编写controller,service,serviceImpl,dao,entity
3.1 entity
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.math.BigDecimal;
@Data
@Entity
@Where(clause = "del_flag = 0")
@Table(name = "t_scf_item_data")
public class ItemData{
private static final long serialVersionUID = 1L;
@TableId
@ApiModelProperty(value = "唯一标识")
private String id = String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
@ApiModelProperty(value = "创建者")
@CreatedBy
private String createBy;
@CreatedDate
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@ApiModelProperty(value = "创建时间")
private Date createTime;
@ApiModelProperty(value = "项目编号")
private String itemNo;
@ApiModelProperty(value = "项目名称")
private String itemName;
@ApiModelProperty(value = "删除标志 默认0")
private Integer delFlag = 0;
3.2 dao
import cn.exrick.xboot.modules.item.entity.ItemData;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ItemDataDao{
@Query(value = "select a.item_no,a.item_name,concat(a.create_time),a.create_by from t_scf_item_data a where a.del_flag = 0 limit 5",nativeQuery = true)
List<List<String>> findAllObject();
@Query(value = "select a.item_no,a.item_name,concat(a.create_time),a.create_by from t_scf_item_data a where a.del_flag = 0 and a.id in ?1 limit 5",nativeQuery = true)
List<List<String>> findByIds(List<String> idList);
3.3 service
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public interface TestService {
void exportExcel(List<String> idList, HttpServletResponse response);
3.4 serviceImpl
import cn.exrick.xboot.common.utils.ExcelUtil;
import cn.exrick.xboot.modules.item.dao.ItemDataDao;
import cn.exrick.xboot.modules.item.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Transactional
@Service
public class TestServiceImpl implements TestService {
@Autowired
private ItemDataDao itemDataDao;
@Override
public void exportExcel(List<String> idList, HttpServletResponse response) {
List<List<String>> dataList = new ArrayList<>();
if(idList == null || idList.size() == 0){
dataList = itemDataDao.findAllObject();
}else{
dataList = itemDataDao.findByIds(idList);
List<String> titleList = Arrays.asList("序号","项目编码", "项目名称", "创建时间", "创建人");
ExcelUtil.uploadExcelAboutUser(response,"apply.xlsx",titleList,dataList);
3.5 controller
import cn.exrick.xboot.modules.item.service.TestService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private TestService testService;
@RequestMapping(value = "/exportExcel", method = RequestMethod.POST)
@ApiOperation(value = "导出excel",produces="application/octet-stream")
public void exportCorpLoanDemand(@RequestBody Map<String,List<String>> map, HttpServletResponse response){ ;
log.info("测试:{}",map);
testService.exportExcel(map.get("list"),response);
近期接到了一个小需求,要将系统中的数据导出为Excel,且能将Excel数据导入到系统。对于大多数研发人员来说,这算是一个最基本的操作了。但是……我居然有点方!好多年没有实操这种基础的功能了。我对于excel导入导出的印象还停留在才入行时的工作经历。配模板,建对应的实体类,写输入输出流…代码繁琐而低效,且不能很好的支持Excel中的格式调整、行列合并等各种复杂操作,每次回想起这些,我都会有一种深深的无力感。然,研发技术的更新换代堪称日新月异。这么多年过去了,也该有更优雅的方式实现这些功能了吧!
SpringBoot返回字符串的方式也是有两种,一种是通过@ResponseBody 和@RequestMapping(value = "/request/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") 中的produces = "application/json;charset=UTF-8" 来设定返回的数据类型是json,utf-8编码,第二种方式,是通过response的方式,直接写到客.
list需要有一个对应的实体类,可以通过ExcelProperty注解来设置列名,可以通过ExcelIgnore注解来忽略某个属性。前端可以通过该接口直接获取xlsx信息,通过HttpServletResponse直接返回数据流。自适应设置excel中的的每个列宽。Excel对应实体类。
需要注意的是,无论使用哪种方法,都需要将Excel文档写入HTTP响应中,并设置正确的Content-Type和Content-Disposition头信息,以确保浏览器能够正确地识别Excel文档并下载它。
web开发项目,经常会有导出和导出excel文件的需求。如何导出(下载到excel文件)和导入excel(从excel向系统导入数据)?excel文件的类型有.xlsexcel 2007之前的格式,包含2007.xlsxexcel 2007之后的格式,内存占用更小。.csv该文件可以以txt形式读取,内容之间用英文逗号隔开。注意:本文只涉及到xls和xlsx文件的导入和导出。csv文件的实质就是txt,所以本文不做介绍。.....................