Java实现excel数据导出

所需导入包

import static org.apache.poi.ss.usermodel.CellType.STRING;


import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import io.renren.modules.cms.entity.CmsDataEntity;
import io.renren.modules.cms.service.CmsDataService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import io.renren.common.annotation.SysLog;
import io.renren.common.lang.DateUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.excel.ExcelUtils;
import io.renren.modules.sys.controller.BaseController;

Controller层

/**
 * 导出月度数据列表信息Excel
 *
 * @param params
 * @param response
 */
@RequestMapping("/export")
public void exportExcel(@RequestBody Map<String, Object> params, HttpServletResponse response) {
    // 创建excel
    try {
        // 获取模板Excel数据
        ClassPathResource classPathResource = new ClassPathResource("/template/templateList.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        XSSFCellStyle commonCellStyle = ExcelUtils.createCellStyle(workbook);
        XSSFCellStyle percentCellStyle = ExcelUtils.createCellStyle(workbook);
        percentCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
        // 设置标题栏信息
        String dataTag = "清单信息" + DateUtils.getDate();
        // 创建头部栏目
        List<CmsDataEntity> list = cmsDataService.findList(params);

        if (CollectionUtils.isNotEmpty(list)) {
            // 创建具体内容行,具体填充信息见templateList.xls模板
            for (int i = 0; i < list.size(); i++) {
                XSSFRow contentRow = sheet.createRow((i + 1));
                ExcelUtils.createCell(contentRow, 0, commonCellStyle, STRING, StringUtils.trimToEmpty(list.get(i).getKpiName()));
                ExcelUtils.createCell(contentRow, 1, commonCellStyle, STRING, list.get(i).getKpiValue());
                ExcelUtils.createCell(contentRow, 2, commonCellStyle, STRING, list.get(i).getCityName());
                ExcelUtils.createCell(contentRow, 3, commonCellStyle, STRING, list.get(i).getBizMonth());
                ExcelUtils.createCell(contentRow, 4, commonCellStyle, STRING, list.get(i).getBizDay());
                ExcelUtils.createCell(contentRow, 5, commonCellStyle, STRING, list.get(i).getResult());
                ExcelUtils.createCell(contentRow, 6, commonCellStyle, STRING, list.get(i).getReferId());
                ExcelUtils.createCell(contentRow, 7, commonCellStyle, STRING, list.get(i).getBatchNo());
            }
        }

        // 输出Excel数据
        String filename = dataTag + ".xlsx";
        ExcelUtils.writeData(response, workbook, filename);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

service层

/**
 * 导出Cms指定指标数据信息
 *
 * @param params
 * @return
 */
List<CmsDataEntity> findList(Map<String, Object> params);

serviceImpl层

/**
 * 导出Cms指定指标数据信息
 *
 * @param params
 * @return
 */
@Override
public List<CmsDataEntity> findList(Map<String, Object> params) {
    String kpiName = Convert.toStr(params.get("kpiName"));
    String cityId = Convert.toStr(params.get("cityId"));
    String teamId = Convert.toStr(params.get("teamId"));
    String bizMonth = Convert.toStr(params.get("bizMonth"));
    List<CmsDataEntity> cmsDataList = this.selectList(new EntityWrapper<CmsDataEntity>().like(StringUtils.isNotBlank(kpiName), "kpi_name", kpiName)
            .eq(StringUtils.isNotBlank(cityId), "city_id", cityId)
            .eq(StringUtils.isNotBlank(teamId), "team_id", teamId)
            .eq(StringUtils.isNotBlank(bizMonth), "biz_month", bizMonth).orderBy("biz_month", false)
            .orderBy("team_id", true).orderBy("kpi_id", true));
    if (CollectionUtils.isNotEmpty(cmsDataList)) {
        // 获取所属地市区域map
        Map<String, String> dictMap = sysDictService.findMap(Constant.SYS_DICT_LOCATION);
        for (CmsDataEntity cmsData : cmsDataList) {
            cmsData.setCityName(dictMap.get(cmsData.getCityId()));
        }
    }
    return cmsDataList;
}

前端vue

// 导出数据

    exportHandle () {

      this.$http({

        url: this.$http.adornUrl(

          `/cms/data/export`

        ),

        responseType: 'blob',

        method: "post",

        data: this.$http.adornData({

          kpiName: this.dataForm.kpiName,

          cityId: this.dataForm.cityId,

          teamId: this.dataForm.teamId,

          bizMonth: this.dataForm.bizMonth

        }, true)

      }).then(res => {

        console.log(res);

        let blob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});

        let fileName = decodeURI(res.headers['filename']);

        if (window.navigator.msSaveOrOpenBlob) {

          navigator.msSaveBlob(blob, fileName)

        } else {

          let link = document.createElement('a')

          link.href = window.URL.createObjectURL(blob)

          link.download = fileName

          link.click()

            //释放内存

          window.URL.revokeObjectURL(link.href)

        }

      }).catch(res => {

         console.log(res)

      });

    }

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值