web后台生成excel下载

excel依赖(内置了poi,生成excel调用的就是poiAPI)

        <dependency>
			<groupId>com.monitorjbl</groupId>
			<artifactId>xlsx-streamer</artifactId>
			<version>2.0.0</version>
		</dependency>

swagger跟springboot依赖自己添加吧.

逻辑代码:

import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
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.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;

@Service
public class DownLoadExcelService {
     

    private static Logger logger = LoggerFactory.getLogger(DownLoadExcelService.class);

    public void downExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
     
        SXSSFWorkbook workbook = null;
        OutputStream os = null;
        try {
     
            //SXSSFSheet专门生成07版本的excel(.xlxs),并且解决数据量稍微大一点就内存溢出的问题
            workbook = new SXSSFWorkbook();
            //构建表头;
            ArrayList<String> head = new ArrayList<String>();
            head.add("名字");
            head.add("年龄");
            //构建数据集
            ArrayList<ArrayList<String>> datas = new ArrayList<>();
            ArrayList<String> data1 = new ArrayList<>();
            data1.add("张三");
            data1.add("18");
            ArrayList<String> data2 = new ArrayList<>();
            data2.add("李四");
            data2.add("19");
            datas.add(data1);
            datas.add(data2);
            //以上准备好了要生成excel的内容

            //下面生成excel内容
            SXSSFSheet sheet = workbook.createSheet("sheet");
            SXSSFRow firstRow = sheet.createRow(0);
            //构建首行的stule(居中,粗体)
            CellStyle FirstRowCellStyle = workbook.createCellStyle();
            FirstRowCellStyle.setAlignment(HorizontalAlignment.CENTER);
            Font font = workbook.createFont();
            font.setBold(true);
            FirstRowCellStyle.setFont(font);

            //生成表头
            for (int i = 0; i < head.size(); i++) {
     
                String headCloumn = head.get(i);
                SXSSFCell cell = firstRow.createCell(i);
                cell.setCellStyle(FirstRowCellStyle);
                cell.setCellValue(headCloumn);
            }

            //生成数据
            for (int i = 0; i < datas.size(); i++) {
     
                SXSSFRow row = sheet.createRow(i + 1);
                ArrayList<String> oneDataList = datas.get(i);
                for (int j = 0; j < oneDataList.size(); j++) {
     
                    String value = oneDataList.get(j);
                    SXSSFCell cell = row.createCell(j);
                    cell.setCellValue(value);
                }
            }
            String fileName = "我的excel" + System.currentTimeMillis() + ".xlsx";
            //获取response输出流,将excel输出到浏览器
            os = getOutputStream(request, response,fileName);
            workbook.write(os);
            logger.info("文件下载成功");
        } catch (Exception e) {
     
            e.printStackTrace();
            logger.error("文件下载失败");
        } finally {
     
            //关流
            os.close();
            workbook.close();
        }

    }

    public OutputStream getOutputStream(HttpServletRequest request, HttpServletResponse response,String fileName) throws Exception {
     
    
        //设置浏览器接收类型
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "no-cache");

        //下面这一步是为了解决浏览器文件下载文件名乱码的问题
        //注意如果使用swagger测试接口,swagger中文件名很可能是乱码的,需要直接用浏览器url访问测试.
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
     
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
     
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        //获取输出流
        OutputStream outputStream = response.getOutputStream();

        return outputStream;
    }
}

controller

import com.tianshi.project.tdhy.service.DownLoadExcelService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/down")
public class DownExcelController {
     

    @Autowired
    private DownLoadExcelService  downLoadExcelService;

    @ApiOperation(value="excel下载",notes = "")
    @GetMapping(value="/excel")
    public void downExcel(HttpServletRequest request,
                               HttpServletResponse response
    ) throws IOException {
     
        downLoadExcelService.downExcel(request,response);
    }
}

打开浏览器访问:
http://localhost:8080/down/excel
web后台生成excel下载_第1张图片
web后台生成excel下载_第2张图片
再次强调一下,通过swagger调用接口下载的文件名中文可能乱码,我未解决swagger下载的乱码问题,因为swagger只是测试而已,没有必要.

你可能感兴趣的:(spring,boot,java,excel,java,spring,boot)