Java+Vue导出Excel

10 篇文章 0 订阅

Vue

<a id="download" />

async downloadFktz() {
      const res = await riskStandingBookApi.exportFktz(this.queryForm)
      if (res.code === 200) {
        document.getElementById('download').setAttribute('href', 'data:xlsx;base64,' + res.data)
        document.getElementById('download').setAttribute('download', 'a.xlsx')
        document.getElementById('download').click()
        this.$message.success(res.msg)
      } else {
        this.$message.error(res.msg)
      }
    }

Java


        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.12</version>
        </dependency>

package com.xxx.xxx.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ExcelUtil {
    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
    public static final String EMPTY = "";
    public static final String POINT = ".";
    public static SimpleDateFormat sdf =   new SimpleDateFormat("yyyy/MM/dd");

    public static String getValue(Cell cell){
        if(cell == null){
            return "";
        }
        String cellValue = "";
        int cellType=cell.getCellType();
        switch (cellType) {
            case Cell.CELL_TYPE_NUMERIC: // 数字
                short format = cell.getCellStyle().getDataFormat();
                if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = null;
                    //System.out.println("cell.getCellStyle().getDataFormat()="+cell.getCellStyle().getDataFormat());
                    if (format == 20 || format == 32) {
                        sdf = new SimpleDateFormat("HH:mm");
                    } else if (format == 14 || format == 31 || format == 57 || format == 58) {
                        // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                        double value = cell.getNumericCellValue();
                        Date date = DateUtil
                                .getJavaDate(value);
                        cellValue = sdf.format(date);
                    }else {// 日期
                        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                    try {
                        cellValue = sdf.format(cell.getDateCellValue());// 日期
                    } catch (Exception e) {
                        try {
                            throw new Exception("exception on get date data !".concat(e.toString()));
                        } catch (Exception e1) {
                            e1.printStackTrace();
                        }
                    }finally{
                        sdf = null;
                    }
                }  else {
                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue()).setScale(8,BigDecimal.ROUND_HALF_UP);
                    cellValue = bd.toPlainString();// 数值 这种用BigDecimal包装再获取plainString,可以防止获取到科学计数值
                }
                break;
            case Cell.CELL_TYPE_STRING: // 字符串
                cellValue = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BOOLEAN: // Boolean
                cellValue = cell.getBooleanCellValue()+"";;
                break;
            case Cell.CELL_TYPE_FORMULA: // 公式
                cellValue = cell.getCellFormula();
                break;
            case Cell.CELL_TYPE_BLANK: // 空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: // 故障
                cellValue = "ERROR VALUE";
                break;
            default:
                cellValue = "UNKNOW VALUE";
                break;
        }
        return cellValue;
    }

    public static Map<String,Integer> getCollIndexNew(Row row){
        Map<String,Integer> map = new HashMap<>();
        for(int i = 0;i<row.getLastCellNum();i++){
            map.put(getValue(row.getCell(i)),i);
        }
        return map;
    }


    public static XSSFCellStyle getStyle(XSSFWorkbook workbook, short boldWeight, short fontHeight, short fontColor, short alignment,
                                         short verticalAlignment, short borderBottom, short borderLeft, short borderRight, short borderTop, String dataFormat,
                                         boolean warpText, short fillPattern, XSSFColor xssfColor){
        try {
            Font font = workbook.createFont();
            font.setFontHeightInPoints(fontHeight);
            font.setFontName("黑体");
            font.setColor(fontColor);

            XSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(alignment);
            style.setVerticalAlignment(verticalAlignment);
            style.setFont(font); // 调用字体样式对象
            style.setWrapText(false);
            if(borderBottom != 0) {
                style.setBorderBottom(borderBottom);
                style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderLeft != 0) {
                style.setBorderLeft(borderLeft);
                style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderRight != 0) {
                style.setBorderRight(borderRight);
                style.setRightBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderTop != 0) {
                style.setBorderTop(borderTop);
                style.setTopBorderColor(IndexedColors.BLACK.getIndex());
            }
            style.setWrapText(warpText);
            if(fillPattern != 0) {
                style.setFillPattern(fillPattern);
            }
            if(xssfColor != null) {
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillForegroundColor(xssfColor);
            }
            if(StringUtils.isNotBlank(dataFormat)) {
                DataFormat df = workbook.createDataFormat();
                style.setDataFormat(df.getFormat(dataFormat));
            }
            return style;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    public static XSSFCellStyle getStyle(XSSFWorkbook workbook,short boldWeight,short fontHeight,short fontColor,short alignment,
                                         short verticalAlignment,short borderBottom,short borderLeft,short borderRight,short borderTop,String dataFormat,
                                         boolean warpText,short fillPattern,short fillForegroundColor){
        try {
            Font font = workbook.createFont();
            font.setFontHeightInPoints(fontHeight);
            font.setFontName("黑体");
            font.setColor(fontColor);
            XSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(alignment);
            style.setVerticalAlignment(verticalAlignment);
            style.setFont(font); // 调用字体样式对象
            style.setWrapText(false);
            if(borderBottom != 0) {
                style.setBorderBottom(borderBottom);
                style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderLeft != 0) {
                style.setBorderLeft(borderLeft);
                style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderRight != 0) {
                style.setBorderRight(borderRight);
                style.setRightBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderTop != 0) {
                style.setBorderTop(borderTop);
                style.setTopBorderColor(IndexedColors.BLACK.getIndex());
            }
            style.setWrapText(warpText);
            if(fillPattern != 0) {
                style.setFillPattern(fillPattern);
            }
            if(fillForegroundColor != 0) {
                style.setFillForegroundColor(fillForegroundColor);
            }
            if(StringUtils.isNotBlank(dataFormat)) {
                DataFormat df = workbook.createDataFormat();
                style.setDataFormat(df.getFormat(dataFormat));
            }
            return style;
        }catch (Exception e){
            return null;
        }
    }

    public static CellStyle getStyle(Workbook workbook,short boldWeight,short fontHeight,short fontColor,short alignment,
                                     short verticalAlignment,short borderBottom,short borderLeft,short borderRight,short borderTop,String dataFormat,
                                     boolean warpText,short fillPattern,short fillForegroundColor){
        try {
            Font font = workbook.createFont();
            font.setFontHeightInPoints(fontHeight);
            font.setFontName("黑体");
            font.setColor(fontColor);
            font.setBoldweight(boldWeight);//0.8
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(alignment);
            style.setVerticalAlignment(verticalAlignment);
            style.setFont(font); // 调用字体样式对象
            style.setWrapText(false);
            if(borderBottom != 0) {
                style.setBorderBottom(borderBottom);
                style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderLeft != 0) {
                style.setBorderLeft(borderLeft);
                style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderRight != 0) {
                style.setBorderRight(borderRight);
                style.setRightBorderColor(IndexedColors.BLACK.getIndex());
            }
            if(borderTop != 0) {
                style.setBorderTop(borderTop);
                style.setTopBorderColor(IndexedColors.BLACK.getIndex());
            }
            style.setWrapText(warpText);
            if(fillPattern != 0) {
                style.setFillPattern(fillPattern);
            }
            if(fillForegroundColor != 0) {
                style.setFillForegroundColor(fillForegroundColor);
            }
            if(StringUtils.isNotBlank(dataFormat)) {
                DataFormat df = workbook.createDataFormat();
                style.setDataFormat(df.getFormat(dataFormat));
            }
            return style;
        }catch (Exception e){
            return null;
        }
    }


    /**
     * 获得path的后缀名
     * @param path
     * @return
     */
    public static String getPostfix(String path){
        if(path==null || EMPTY.equals(path.trim())){
            return EMPTY;
        }
        if(path.contains(POINT)){
            return path.substring(path.lastIndexOf(POINT)+1,path.length());
        }
        return EMPTY;
    }
    /**
     * 单元格格式
     * @param
     * @return
     */
    @SuppressWarnings({ "static-access", "deprecation" })
//    public static String getHValue(HSSFCell hssfCell){
//        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
//            return String.valueOf(hssfCell.getBooleanCellValue());
//        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
//            String cellValue = "";
//            if(HSSFDateUtil.isCellDateFormatted(hssfCell)){
//                Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());
//                cellValue = sdf.format(date);
//            }else{
//                DecimalFormat df = new DecimalFormat("#.########");
//                cellValue = df.format(hssfCell.getNumericCellValue());
//                String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
//                if(strArr.equals("00")){
//                    cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
//                }
//            }
//            return cellValue;
//        } else {
//            hssfCell.setCellType(CellType.STRING);
//            return String.valueOf(hssfCell.getStringCellValue());
//        }
//    }
    /**
     * 单元格格式
     * @param xssfCell
     * @return
     */
//    public static String getXValue(Cell xssfCell){
//        if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
//            return String.valueOf(xssfCell.getBooleanCellValue());
//        } else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
//            String cellValue = "";
//            if(XSSFDateUtil.isCellDateFormatted(xssfCell)){
//                Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());
//                cellValue = sdf.format(date);
//            }else{
//                DecimalFormat df = new DecimalFormat("#.########");
//                cellValue = df.format(xssfCell.getNumericCellValue());
//                String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
//                if(strArr.equals("00")){
//                    cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
//                }
//            }
//            return cellValue;
//        } else {
//            xssfCell.setCellType(CellType.STRING);
//            return String.valueOf(xssfCell.getStringCellValue());
//        }
//    }
    /**
     * 自定义xssf日期工具类
     *
     */
    static class XSSFDateUtil extends DateUtil {
        protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
            return DateUtil.absoluteDay(cal, use1904windowing);
        }
    }
}


	@RequestMapping(value = "/exportFktz",method = RequestMethod.POST)
	@ResponseBody
	public RestResponse<String> exportFktz(@RequestBody TrsRiskStandingBookSearchDto model){
		try {
			String result = trsRiskStandingBookService.exportFktz(model);
			return new RestResponse<String>(RestResponse.SUCCESS_CODE,"导出成功", result);
		} catch (Exception e) {
			e.printStackTrace();
			return new RestResponse<String>(RestResponse.FAILURE_CODE,"导出失败" + e.getMessage(),null);
		}
	}
    @Override
    public String exportFktz(TrsRiskStandingBookSearchDto dto) {
        //查询用户拥有权限的项目
        long userId = StpUtil.getLoginIdAsLong();
        List<TrsBasicsProjectModel> basicsProjectModelList = trsBasicsProjectMapper.queryUserProject(userId);
        LambdaQueryWrapper<TrsRiskStandingBookModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CollUtil.isNotEmpty(dto.getProjectIds()), TrsRiskStandingBookModel::getProjectId, dto.getProjectIds());
        queryWrapper.in(!CollectionUtils.isEmpty(basicsProjectModelList), TrsRiskStandingBookModel::getProjectId
                , basicsProjectModelList.stream().map(BaseModel::getId).collect(Collectors.toList()));
        queryWrapper.in(CollUtil.isNotEmpty(dto.getStrategyIds()), TrsRiskStandingBookModel::getStrategyId, dto.getStrategyIds());
        queryWrapper.ge(StringUtils.isNotBlank(dto.getBeginDate()), TrsRiskStandingBookModel::getDate, dto.getBeginDate());
        queryWrapper.le(StringUtils.isNotBlank(dto.getEndDate()), TrsRiskStandingBookModel::getDate, dto.getEndDate());
        List<TrsRiskStandingBookModel> modelList = trsRiskStandingBookMapper.selectList(queryWrapper);
        modelList = modelList.stream().sorted(Comparator.comparing(TrsRiskStandingBookModel::getDate).reversed()).collect(Collectors.toList());
        for (TrsRiskStandingBookModel bookModel : modelList) {
            translateFktz(bookModel);
        }
        if (!CollectionUtils.isEmpty(modelList)) {
            XSSFWorkbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("a");
            sheet.setDefaultColumnWidth(15);
            int rowNum = 0;
            Row row0 = sheet.createRow(rowNum++);
            Cell cell0_0 = row0.createCell(0);
            cell0_0.setCellValue("1");
            cell0_0.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
            Cell cell0_1 = row0.createCell(1);
            cell0_1.setCellValue("2");
            cell0_1.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
            Cell cell0_2 = row0.createCell(2);
            cell0_2.setCellValue("3");
            cell0_2.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
            Cell cell0_3 = row0.createCell(3);
            cell0_3.setCellValue("4");
            cell0_3.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
            Cell cell0_4 = row0.createCell(4);
            cell0_4.setCellValue("5");
            cell0_4.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));

            Cell cell0_5 = row0.createCell(5);
            cell0_5.setCellValue("6");
            cell0_5.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));

            Cell cell0_6 = row0.createCell(6);
            cell0_6.setCellValue("7");
            cell0_6.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));


            Cell cell0_7 = row0.createCell(7);
            cell0_7.setCellValue("8");
            cell0_7.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
            Cell cell0_8 = row0.createCell(8);
            cell0_8.setCellValue("9");
            cell0_8.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));
            Cell cell0_9 = row0.createCell(9);
            cell0_9.setCellValue("10");
            cell0_9.setCellStyle(ExcelUtil.getStyle(workbook, Font.BOLDWEIGHT_BOLD, (short) 10, HSSFColor.BLACK.index, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER, (short) 0, (short) 0, (short) 0, (short) 0, "", false, (short) 0, null));

            for (TrsRiskStandingBookModel bookModel : modelList) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(bookModel.getDate());
                row.createCell(1).setCellValue(bookModel.getProjectName());
                row.createCell(2).setCellValue(bookModel.getStrategyType());
                row.createCell(3).setCellValue(bookModel.getStrategyName());
                row.createCell(4).setCellValue(null == bookModel.getPosition()
                        ? null : bookModel.getPosition().setScale(2, BigDecimal.ROUND_HALF_UP).toString());

                if (StringUtils.isNotBlank(dto.getMoneyUnit()) && "万元".equals(dto.getMoneyUnit())) {
                    row.createCell(5).setCellValue(null == bookModel.getClyk()
                            ? null : bookModel.getClyk().divide(new BigDecimal("10000"),2,BigDecimal.ROUND_HALF_UP).toString());
                    row.createCell(6).setCellValue(null == bookModel.getClykdrzl()
                            ? null : bookModel.getClykdrzl().divide(new BigDecimal("10000"),2, BigDecimal.ROUND_HALF_UP).toString());
                }else {
                    row.createCell(5).setCellValue(null == bookModel.getClyk()
                            ? null : bookModel.getClyk().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    row.createCell(6).setCellValue(null == bookModel.getClykdrzl()
                            ? null : bookModel.getClykdrzl().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                }

                row.createCell(7).setCellValue(null == bookModel.getExposure()
                        ? null : bookModel.getExposure().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                row.createCell(8).setCellValue(null == bookModel.getHedgingRate()
                        ? null : bookModel.getHedgingRate().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                row.createCell(9).setCellValue(bookModel.getRemark());
            }
            String fileTempPath = System.getProperty("user.dir") + File.separator + "tempExcel";
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                File f = new File(fileTempPath);
                if (!f.exists()) {//如果文件夹不存在
                    f.mkdir();//创建文件夹
                }
                FileOutputStream fos = new FileOutputStream(fileTempPath + File.separator + sdf.format(now) + "a.xlsx");
                workbook.write(fos);
                fos.flush();
                fos.close();
                File file = new File(fileTempPath + File.separator + sdf.format(now) + "a.xlsx");
                FileInputStream inputFile = new FileInputStream(file);
                byte[] buffer = new byte[(int) file.length()];
                inputFile.read(buffer);
                inputFile.close();
                return new BASE64Encoder().encode(buffer);
            } catch (Exception e) {
                throw new RuntimeException("生成Excel异常", e);
            }
        }
        return null;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值