ExportController.java 7.99 KB
package com.bckefu.controller;

import com.bckefu.entity.ContactsEntity;
import com.bckefu.entity.ContactsGroup;
import com.bckefu.excel.ExcelExportUtil;
import com.bckefu.excel.entity.ExportParams;
import com.bckefu.excel.entity.enmus.ExcelType;
import com.bckefu.excel.entity.params.ExcelExportEntity;
import com.bckefu.excel.entity.vo.ExcelConstants;
import com.bckefu.excel.handler.inter.IExcelExportServer;
import com.bckefu.excel.view.AbstractExcelView;
import com.bckefu.excel.view.BaseView;
import com.uccc.oss.service.OssService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author : caoliang
 * @date : 2017/11/6:下午3:51
 */

@RestController
@RequestMapping("export")
public class ExportController {

    @Autowired
    private IExcelExportServer excelExportServer;
    @Autowired
    private OssService ossService;


    @ApiOperation(value = "导出bigData", tags = "1.2.1")
    @GetMapping("bigData")
    public void downloadByPoiBaseView(ModelMap map, HttpServletRequest request,
                                      HttpServletResponse response) {
        ExportParams params = new ExportParams("测试sheetName", ExcelType.XSSF);
        //params.setFreezeCol(0); //冻结列
        params.setFreezeRow(1); //冻结行
        map.put(ExcelConstants.CLASS, ContactsEntity.class);
        map.put(ExcelConstants.PARAMS, params);
        //就是我们的查询参数,会带到接口中,供接口查询使用
        map.put(ExcelConstants.DATA_PARAMS, new HashMap<String, String>());
        map.put(ExcelConstants.DATA_INTER, excelExportServer);
        BaseView.render("测试下载", map, request, response, ExcelConstants.POI_BIG_EXCEL_VIEW);
    }

    @ApiOperation(value = "视图导出mapData", tags = "1.2.2")
    @GetMapping("viewMapData")
    public void mapData(ModelMap modelMap, HttpServletRequest request,
                        HttpServletResponse response) {
        List<ExcelExportEntity> entity = new ArrayList<ExcelExportEntity>();
        entity.add(new ExcelExportEntity("姓名", "name"));
        entity.add(new ExcelExportEntity("性别", "sex"));
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map;
        for (int i = 0; i < 10; i++) {
            map = new HashMap<String, Object>();
            map.put("name", "1" + i);
            map.put("sex", "2" + i);
            list.add(map);
        }
        ExportParams params = new ExportParams("测试", ExcelType.XSSF);
        params.setFreezeRow(1);
        modelMap.put(ExcelConstants.MAP_LIST, list);
        modelMap.put(ExcelConstants.ENTITY_LIST, entity);
        modelMap.put(ExcelConstants.PARAMS, params);
        BaseView.render("map导出", modelMap, request, response, ExcelConstants.POI_MAP_EXCEL_VIEW);
    }

    @ApiOperation(value = "直接导出mapData", tags = "1.2.3")
    @GetMapping("simpleMapData")
    public void simpleMapData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<ExcelExportEntity> entityList = new ArrayList<ExcelExportEntity>();
        entityList.add(new ExcelExportEntity("姓名", "name"));
        entityList.add(new ExcelExportEntity("性别", "sex"));
        entityList.add(new ExcelExportEntity("年龄", "age"));
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map;
        for (int i = 0; i < 10; i++) {
            map = new HashMap<String, Object>();
            map.put("name", "1" + i);
            map.put("sex", "2" + i);
            map.put("age", i);
            list.add(map);
        }
        ExportParams exportParams = new ExportParams("测试", ExcelType.XSSF);
        exportParams.setFreezeRow(1);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entityList, list);

        String fileName = RandomStringUtils.randomAlphanumeric(6);
        if (workbook instanceof HSSFWorkbook) {
            fileName += AbstractExcelView.HSSF;
        } else {
            fileName += AbstractExcelView.XSSF;
        }
        if (BaseView.isIE(request)) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setHeader("content-disposition", "attachment;filename=" + fileName);
        response.setContentType(AbstractExcelView.CONTENT_TYPE);
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
    }


    @ApiOperation(value = "oss导出", tags = "1.3.1")
    @GetMapping("ossDownload")
    public ResponseEntity ossDownload() {
        List<ContactsEntity> list = new ArrayList<ContactsEntity>();
        ExportParams params = new ExportParams("测试sheetName", ExcelType.XSSF);
        params.setFreezeRow(1);
        ContactsEntity client = null;
        for (int i = 0; i < 100; i++) {
            client = new ContactsEntity();
            client.setBirthday(new Date());
            client.setClientName("小明" + i);
            client.setClientPhone("186129831" + i);
            client.setCreateBy("hello world");
            client.setId("1" + i);
            client.setRemark("测试" + i);
            client.setCts(new Date());
            ContactsGroup group = new ContactsGroup();
            group.setGroupName("测试" + i);
            client.setGroup(group);
            list.add(client);
        }
        String s = saveOssFile(params, ContactsEntity.class, list);
        return new ResponseEntity(s, HttpStatus.OK);
    }


    /**
     * OSS上传
     *
     * @param exportParams
     * @param pojoClass
     * @param list
     * @return
     */
    private String saveOssFile(ExportParams exportParams, Class<?> pojoClass, List list) {
        Workbook workbook = ExcelExportUtil.exportBigExcel(exportParams, pojoClass, list);
        StringBuffer buffer = new StringBuffer();
        buffer.append("bckefu").append("/").append(LocalDate.now().toString()).append("/");
        buffer.append(LocalDateTime.of(LocalDate.now(), LocalTime.now()).format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
        if (workbook instanceof HSSFWorkbook) {
            buffer.append(AbstractExcelView.HSSF);
        } else {
            buffer.append(AbstractExcelView.XSSF);
        }
        try {
            /**
             * 普通文件上传
             */
            /*File file = new File(buffer.toString());
            FileOutputStream os = new FileOutputStream(file);
            workbook.write(os);
            os.close();
            String s = ossService.uploadFile(buffer.toString() , new File(buffer.toString()));
            System.out.println(s);*/

            /**
             * 输入流上传
             */
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            ossService.uploadByStream(buffer.toString(), inputStream);
            outputStream.close();
            inputStream.close();
            return "https://cc-bckefu-dev.oss-cn-shanghai.aliyuncs.com/" + buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}