Java自定义Excel模板导入导出

本文介绍了如何使用阿里巴巴的EasyExcel库和Apache POI库来实现Excel文件的导入和导出。在EasyExcel示例中,展示了读取和写入数据的过程,而在Apache POI部分,详细演示了创建工作簿、设置样式、填充数据以及导出Excel文件的步骤。内容涵盖了单元格样式、合并单元格以及数据填充等关键操作。
摘要由CSDN通过智能技术生成

1、使用阿里com.alibaba.excel.EasyExcel导出

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.ruoyi.admin.cstc.result.Result;
import com.ruoyi.framework.excel.ExcelUtil;
import com.ruoyi.framework.excel.ExcelWebRead;
import com.ruoyi.framework.utils.FileDyUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.lite.base.IController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/excel")
@Slf4j
@AllArgsConstructor
public class ExcelController implements IController {

    /**
     * 模板下载
     *
     * @return
     */
    @SneakyThrows
    @RequestMapping("/templateDownload")
    public Object templateDownload() {
        String fileName = "test.xlsx";
        //Windows
        String filePath = ExcelUtil.getTemplate(fileName);
        //linux 防止读取jar包目录资源出错,jar包所在同目录下创建以下目录
        //ClassPathResource resource = new ClassPathResource("static/excel/" + fileName);
        //String filePath = resource.getPath();
        //import net.dreamlu.mica.lite.base.IController;
        return download(new File(filePath), fileName);
    }

    /**
     * 导入
     *
     * @param file
     * @return
     */
    @SneakyThrows
    @PostMapping("/importExcel")
    public Result importExcel(MultipartFile file) {
        // 为保证数据一次性导入,不要超过3000条
        EasyExcel.read(file.getInputStream(), ExcelDemo.class, new ExcelWebRead<ExcelDemo>(dataList -> {
            for (ExcelDemo demoData : dataList) {
                log.info("读取到一条数据{}", JSON.toJSONString(demoData));
                //TODO 处理导入
            }
        })).sheet("Sheet1").headRowNumber(2).doRead();//Sheet1页从第三行读取数据
        return Result.SUCCESS();
    }

    /**
     * 导出
     */
    @SneakyThrows
    @GetMapping("/exportExcel")
    public void exportExcel() {
        List<ExcelDemo> dataList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ExcelDemo data = new ExcelDemo();
            data.setString("字符串" + i);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            dataList.add(data);
        }

        EasyExcel.write(FileDyUtils.getOutputStream(DateUtil.now() + ".xlsx"), ExcelDemo.class)
                .sheet("Sheet1")
                .doWrite(dataList);
    }

}
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.Data;

import java.util.Date;

@Data
public class ExcelDemo {

    @ExcelProperty("字符串")
    @ColumnWidth(16)
    private String string;

    @ExcelProperty("日期")
    @ColumnWidth(16)
    private Date date;

    @ExcelProperty("数字")
    @ColumnWidth(16)
    private Double doubleData;

}
import com.ruoyi.framework.utils.FileUtils;

import java.io.File;

public class ExcelUtil {

    /**
     * 获取业务相关导入导出模板, 统一存放路径为:resources/static/excel
     *
     * @param fileName 文件名称
     * @return 文件路径
     */
    public static String getTemplate(String fileName) {
        return FileUtils.getResourcePath()
                + "static"
                + File.separator
                + "excel"
                + File.separator
                + fileName;
    }

}
package com.ruoyi.framework.utils;

import cn.hutool.core.util.ReUtil;

public class FileUtils {

    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-|.\\u4e00-\\u9fa5]+";

    public static String getResourcePath() {
        return FileUtils.class.getResource("/").getPath();
    }

    /**
     * 文件名称验证
     *
     * @param fileName 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isInValidFilename(String fileName) {
        return !ReUtil.isMatch(FILENAME_PATTERN, fileName);
    }

}

 参考:

EasyExcel操作API与示例 - it610.com

Java EasyExcel读取Excel同步返回数据的方法及示例代码-CJavaPy

快速学习-easyExcel大文件读取说明_wx5d0241bb88268的技术博客_51CTO博客

2、使用org.apache.poi导出

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.admin.cstc.assets.assets.entity.CstcAssets;
import com.ruoyi.admin.cstc.assets.assets.service.CstcAssetsService;
import com.ruoyi.admin.cstc.assets.category.service.CstcAssetsCategoryService;
import com.ruoyi.admin.cstc.assets.receive.entity.CstcAssetsReceive;
import com.ruoyi.admin.cstc.assets.receive.entity.CstcRelAssetsReceive;
import com.ruoyi.admin.cstc.assets.receive.service.CstcAssetsReceiveService;
import com.ruoyi.admin.cstc.assets.receive.service.CstcRelAssetsReceiveService;
import com.ruoyi.admin.cstc.result.Result;
import com.ruoyi.system.sys.service.ISysDeptService;
import com.ruoyi.system.sys.service.ISysDictDataService;
import com.ruoyi.system.sys.service.ISysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/excel")
@Slf4j
@AllArgsConstructor
public class ExcelController {

    private final CstcAssetsReceiveService cstcAssetsReceiveService;
    private final CstcRelAssetsReceiveService cstcRelAssetsReceiveService;
    private final CstcAssetsService cstcAssetsService;
    private final ISysDeptService iSysDeptService;
    private final ISysUserService iSysUserService;
    private final ISysDictDataService iSysDictDataService;
    private final CstcAssetsCategoryService cstcAssetsCategoryService;

    /**
     * 资产领用导出
     *
     * @param response
     * @return
     */
    @GetMapping("/receiveExport")
    public Result receiveExport(HttpServletResponse response, Long receiveId) {
        try {
            //新建工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("工作薄");//工作薄名称
            //设置每格数据的样式
            HSSFFont ParamFontStyle = workbook.createFont();
            CellStyle cellParamStyle = workbook.createCellStyle();
            cellParamStyle.setAlignment(HorizontalAlignment.CENTER);//垂直居中
            cellParamStyle.setVerticalAlignment(VerticalAlignment.CENTER);//水平居中
            cellParamStyle.setWrapText(false);//自动换行
            ParamFontStyle.setFontHeightInPoints((short) 13);//字体大小
            ParamFontStyle.setFontName("等线");
            cellParamStyle.setFont(ParamFontStyle);

            //设置表头的样式
            HSSFFont ParamFontStyle1 = workbook.createFont();
            CellStyle cellParamStyle1 = workbook.createCellStyle();
            cellParamStyle1.setAlignment(HorizontalAlignment.LEFT);
            cellParamStyle1.setVerticalAlignment(VerticalAlignment.DISTRIBUTED);
            cellParamStyle1.setWrapText(false);//自动换行
            ParamFontStyle1.setFontHeightInPoints((short) 15);
            ParamFontStyle1.setFontName("黑体");
            ParamFontStyle1.setBold(true);//是否打开加粗
            cellParamStyle1.setFont(ParamFontStyle1);

            //设置标题的样式
            HSSFFont ParamFontStyle2 = workbook.createFont();
            CellStyle cellParamStyle2 = workbook.createCellStyle();
            cellParamStyle2.setAlignment(HorizontalAlignment.CENTER);//垂直居中
            cellParamStyle2.setVerticalAlignment(VerticalAlignment.CENTER);//水平居中
            cellParamStyle2.setWrapText(true);//自动换行
            ParamFontStyle2.setFontHeightInPoints((short) 14);
            ParamFontStyle2.setFontName("黑体");
            ParamFontStyle2.setBold(true);
            cellParamStyle2.setFont(ParamFontStyle2);

            //设置标题的样式
            HSSFFont ParamFontStyle3 = workbook.createFont();
            CellStyle cellParamStyle3 = workbook.createCellStyle();
            cellParamStyle3.setAlignment(HorizontalAlignment.CENTER);//垂直居中
            cellParamStyle3.setVerticalAlignment(VerticalAlignment.CENTER);//水平居中
            cellParamStyle3.setWrapText(true);//自动换行
            ParamFontStyle3.setFontHeightInPoints((short) 18);
            ParamFontStyle3.setFontName("黑体");
            ParamFontStyle3.setBold(true);
            cellParamStyle3.setFont(ParamFontStyle3);

            //定义列的宽度
            //sheet.setDefaultColumnWidth(40 * 1024);默认sheet1.CreateRow(0).Height = 200*20;//宽度
            Short height = 390;
            sheet.setDefaultRowHeight((Short) height);
            sheet.setColumnWidth(0, 5000);
            sheet.setColumnWidth(1, 5000);
            sheet.setColumnWidth(2, 5000);
            sheet.setColumnWidth(3, 5000);
            sheet.setColumnWidth(4, 5000);
            sheet.setColumnWidth(5, 5000);
            sheet.setColumnWidth(6, 5000);
            sheet.setColumnWidth(7, 5000);
            sheet.setColumnWidth(8, 5000);
            sheet.setColumnWidth(9, 5000);
            sheet.setColumnWidth(10, 5000);

            //设置表头
            //固定资产领用单
            HSSFRow rows = sheet.createRow(0);//第一行
            HSSFCell cell = rows.createCell(0);//一列

            //领用单号
            HSSFRow rows1 = sheet.createRow(1);//第二行
            HSSFCell cell1 = rows1.createCell(0);//一列
            //对应的值
            HSSFRow rows7 = sheet.createRow(1);//第二行
            HSSFCell cell7 = rows7.createCell(2);//三列

            //领用日期
            HSSFRow rows2 = sheet.createRow(1);//第二行
            HSSFCell cell2 = rows2.createCell(4);//五列
            //对应的值
            HSSFRow rows8 = sheet.createRow(1);//第二行
            HSSFCell cell8 = rows8.createCell(6);//七列

            //领用部门
            HSSFRow rows3 = sheet.createRow(1);//第二行
            HSSFCell cell3 = rows3.createCell(8);//九列
            //对应的值
            HSSFRow rows9 = sheet.createRow(1);//第二行
            HSSFCell cell9 = rows9.createCell(9);//十列

            //领用人
            HSSFRow rows4 = sheet.createRow(2);//第三行
            HSSFCell cell4 = rows4.createCell(0);//一列
            //对应的值
            HSSFRow rows10 = sheet.createRow(2);//第三行
            HSSFCell cell10 = rows10.createCell(2);//三列

            //导出日期
            HSSFRow rows5 = sheet.createRow(2);//第三行
            HSSFCell cell5 = rows5.createCell(4);//五列
            //对应的值
            HSSFRow rows11 = sheet.createRow(2);//第三行
            HSSFCell cell11 = rows11.createCell(6);//七列

            /*
            //XX日期
            HSSFRow rows6 = sheet.createRow(2);//第三行
            HSSFCell cell6 = rows6.createCell(8);//九列
            //对应的值
            HSSFRow rows12 = sheet.createRow(2);//第二行
            HSSFCell cell12 = rows12.createCell(9);//十列
            */

            //合并单元格     起始行,结束行,起始列,结束列     第一行显示1个10个格的标题所以行就是从0到0,列是从0到9
            CellRangeAddress region = new CellRangeAddress(0, 0, 0, 10);
            sheet.addMergedRegion(region);

            CellRangeAddress region1 = new CellRangeAddress(1, 1, 0, 1);
            sheet.addMergedRegion(region1);
            CellRangeAddress region2 = new CellRangeAddress(1, 1, 2, 3);
            sheet.addMergedRegion(region2);
            CellRangeAddress region3 = new CellRangeAddress(1, 1, 4, 5);
            sheet.addMergedRegion(region3);
            CellRangeAddress region4 = new CellRangeAddress(1, 1, 6, 7);
            sheet.addMergedRegion(region4);
            CellRangeAddress region5 = new CellRangeAddress(1, 1, 9, 10);
            sheet.addMergedRegion(region5);

            CellRangeAddress region6 = new CellRangeAddress(2, 2, 0, 1);
            sheet.addMergedRegion(region6);
            CellRangeAddress region7 = new CellRangeAddress(2, 2, 2, 3);
            sheet.addMergedRegion(region7);
            CellRangeAddress region8 = new CellRangeAddress(2, 2, 4, 5);
            sheet.addMergedRegion(region8);
            CellRangeAddress region9 = new CellRangeAddress(2, 2, 6, 7);
            sheet.addMergedRegion(region9);
            CellRangeAddress region10 = new CellRangeAddress(2, 2, 9, 10);
            sheet.addMergedRegion(region10);

            //标题单元格风格
            cell.setCellStyle(cellParamStyle3);
            cell1.setCellStyle(cellParamStyle2);
            cell2.setCellStyle(cellParamStyle2);
            cell3.setCellStyle(cellParamStyle2);
            cell4.setCellStyle(cellParamStyle2);
            cell5.setCellStyle(cellParamStyle2);
            //cell6.setCellStyle(cellParamStyle2);

            //对应值单元格风格
            cell7.setCellStyle(cellParamStyle);
            cell8.setCellStyle(cellParamStyle);
            cell9.setCellStyle(cellParamStyle);
            cell10.setCellStyle(cellParamStyle);
            cell11.setCellStyle(cellParamStyle);
            //cell12.setCellStyle(cellParamStyle);

            //标题值
            cell.setCellValue("固定资产领用单");
            cell1.setCellValue("领用单号");
            cell2.setCellValue("领用日期");
            cell3.setCellValue("领用部门");
            cell4.setCellValue("领用人");
            cell5.setCellValue("导出日期");
            //cell6.setCellValue("XX日期");


            //TODO 填充数据
            CstcAssetsReceive car = cstcAssetsReceiveService.getById(receiveId);
            //领用单号
            cell7.setCellValue(car.getReceiveNo());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
            //领用时间
            cell8.setCellValue(simpleDateFormat.format(car.getReceiveDate()));
            //领用部门
            String deptName = iSysDeptService.getDeptName(car.getReceiveDeptId());
            cell9.setCellValue(deptName);
            //领用人
            String nickName = iSysUserService.getNickName(car.getReceiveUserId());
            cell10.setCellValue(nickName);
            //导出日期
            cell11.setCellValue(simpleDateFormat.format(new Date()));
            //XX日期
            //cell12.setCellValue(simpleDateFormat.format(new Date()));


            //列名
            HSSFRow row1 = sheet.createRow(3);//下标从0开始,对应excel从第4行插入列表标题
            HSSFCell row1Cell0 = row1.createCell(0);
            row1Cell0.setCellValue("资产编号");
            row1Cell0.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell = row1.createCell(1);
            row1Cell.setCellValue("资产名称");
            row1Cell.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell1 = row1.createCell(2);
            row1Cell1.setCellValue("资产分类");
            row1Cell1.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell2 = row1.createCell(3);
            row1Cell2.setCellValue("品牌及型号");
            row1Cell2.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell3 = row1.createCell(4);
            row1Cell3.setCellValue("所属单位");
            row1Cell3.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell4 = row1.createCell(5);
            row1Cell4.setCellValue("资产规格");
            row1Cell4.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell5 = row1.createCell(6);
            row1Cell5.setCellValue("资产单价");
            row1Cell5.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell6 = row1.createCell(7);
            row1Cell6.setCellValue("资产状况");
            row1Cell6.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell7 = row1.createCell(8);
            row1Cell7.setCellValue("经手人");
            row1Cell7.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell8 = row1.createCell(9);
            row1Cell8.setCellValue("所属项目");
            row1Cell8.setCellStyle(cellParamStyle2);
            HSSFCell row1Cell9 = row1.createCell(10);
            row1Cell9.setCellValue("配置");
            row1Cell9.setCellStyle(cellParamStyle2);


            //TODO 填充数据
            List<CstcRelAssetsReceive> assetsReceiveList = cstcRelAssetsReceiveService.list(new LambdaQueryWrapper<CstcRelAssetsReceive>()
                    .eq(CstcRelAssetsReceive::getAssetsReceiveId, car.getId())
            );
            int sheet1Colume = 0;
            for (CstcRelAssetsReceive hospitalExcel : assetsReceiveList) {
                //TODO 填充数据
                CstcAssets assets = cstcAssetsService.getById(hospitalExcel.getAssetsId());

                HSSFRow row2 = sheet.createRow(sheet1Colume + 4);//下标从0开始,对应excel从第5行插入列表数据值

                HSSFCell row2Cell = row2.createCell(0);
                row2Cell.setCellStyle(cellParamStyle);
                row2Cell.setCellValue(assets.getAssetsNo());//序号

                HSSFCell row2Cell1 = row2.createCell(1);
                row2Cell1.setCellStyle(cellParamStyle);
                row2Cell1.setCellValue(assets.getAssetsName());

                HSSFCell row2Cell2 = row2.createCell(2);
                row2Cell2.setCellStyle(cellParamStyle);
                String assetsTypeName = cstcAssetsCategoryService.getAssetsTypeName(assets.getAssetsTypeId());
                row2Cell2.setCellValue(assetsTypeName);

                HSSFCell row2Cell3 = row2.createCell(3);
                row2Cell3.setCellStyle(cellParamStyle);
                row2Cell3.setCellValue(assets.getBrandModel());

                HSSFCell row2Cell4 = row2.createCell(4);
                row2Cell4.setCellStyle(cellParamStyle);
                //所属单位
                String dictType = "affiliation_unit";
                String dictLabel = iSysDictDataService.selDictName(dictType, assets.getAffiliationUnit());
                row2Cell4.setCellValue(dictLabel);

                HSSFCell row2Cell5 = row2.createCell(5);
                row2Cell5.setCellStyle(cellParamStyle);
                row2Cell5.setCellValue(assets.getAssetsSpec());

                HSSFCell row2Cell6 = row2.createCell(6);
                row2Cell6.setCellStyle(cellParamStyle);
                row2Cell6.setCellValue(assets.getEqPrice().toString());

                //资产状况
                String dictType1 = "assets_state";
                String dictLabel1 = iSysDictDataService.selDictName(dictType1, assets.getAssetsState());
                HSSFCell row2Cell7 = row2.createCell(7);
                row2Cell7.setCellStyle(cellParamStyle);
                row2Cell7.setCellValue(dictLabel1);

                HSSFCell row2Cell8 = row2.createCell(8);
                row2Cell8.setCellStyle(cellParamStyle);
                row2Cell8.setCellValue(assets.getHandledBy());

                HSSFCell row2Cell9 = row2.createCell(9);
                row2Cell9.setCellStyle(cellParamStyle);
                row2Cell9.setCellValue(assets.getAffiliationProject());

                HSSFCell row2Cell10 = row2.createCell(10);
                row2Cell10.setCellStyle(cellParamStyle);
                row2Cell10.setCellValue(assets.getConfiguration());
                sheet1Colume++;
            }
            String fileName = new String(DateUtil.now().getBytes(), "UTF-8") + ".xls";
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.setCharacterEncoding("UTF-8");
            OutputStream os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            try {
                os.close();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return Result.SUCCESS();
    }

}

结果:

参考:Java自定义excel样式并导出(poi)_TuGiant的博客-CSDN博客

转载请注明出处:BestEternity亲笔。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值