Java导出excel基于注解

本文介绍了一种使用JavaScript实现在前端导出数据到Excel的方法,并详细展示了从调用导出函数到后端处理及返回文件的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

js中的方法:

// 导出日志
exportLog:function(e){
            debugger
            fly.top.fly.dialog({
                title: '导出',
                content: '是否导出?',
                width: '240px',
                padding: '30px 20px',
                okValue: '确认',
                cancelValue: '取消',
                ok: function() {
                    util.mask('文件正在导出...');
                    window.location.href=CONTEXTPATH + '/originalhitch/exportLog.do?hitchId=' + id;
                    util.removeMask()
                },
                cancel: true
            });
        },

控制层,我是因为根据id来查询数据的

@RequestMapping(value = "/exportLog.do", produces = "application/json;charset=UTF-8")
@ResponseBody
public String exportLog(HttpServletRequest request,HttpServletResponse response, String hitchId) {
try {
String filepath=request.getRealPath("/")+"upload/";

String path=  originalHitchService.exportItem(hitchId,filepath);
String name="原文挂接详情";
String sux="";
if(path.contains(".")){
sux=path.substring(path.lastIndexOf("."),path.length());
}
OutputStream out = response.getOutputStream();
byte[] fileData = FileUtils.fileToBytes(path);
String filename = new String(
URLEncoder.encode(name+sux, "UTF-8")
.getBytes("UTF-8"),
"ISO8859-1");
response.setHeader("content-disposition", "attachment;filename=" + filename);
// 写明要下载的文件的大小
response.setContentLength(fileData.length);
out.write(fileData);
out.flush();
out.close();
} catch (Exception e) {
logger.error("导出日志异常:" + e.getMessage(), e);
return JSONUtil.error();
}
return JSONUtil.success();
}

实现层方法:

@Override
public String exportItem(String hitchId,String filepath) throws Exception {
List<HsdaOriginalHitchDetail> originalHitchDetails =originalHitchDetailDao.queryListByHitchId(hitchId);
HitchLogExcel hitchLogExcel;
        String path;
        List<HitchLogExcel> list = new ArrayList<>();
        for (HsdaOriginalHitchDetail originalHitchDetail : originalHitchDetails) {
        hitchLogExcel = new HitchLogExcel();
            hitchLogExcel.setFileNum(StringUtil.isNotEmpty(originalHitchDetail.getFileNum()) ? originalHitchDetail.getFileNum() : "");
            hitchLogExcel.setRecordTitle(StringUtil.isNotEmpty(originalHitchDetail.getRecordTitle()) ?originalHitchDetail.getRecordTitle() : "");
            hitchLogExcel.setRecordPageNum(StringUtil.isNotEmpty(originalHitchDetail.getRecordNum()) ?originalHitchDetail.getRecordNum() : "");
            hitchLogExcel.setOriginalNum(StringUtil.isNotEmpty(originalHitchDetail.getOriginalNum()) ?originalHitchDetail.getOriginalNum() : "");
            if (StringUtil.isNotEmpty(originalHitchDetail.getMatchStatus())) {
                hitchLogExcel.setMatchStatus(PublicZdCacheLoadImpl.getDictMc("PPZT", originalHitchDetail.getMatchStatus(), false));
            } else {
            hitchLogExcel.setMatchStatus("");
            }
            if (StringUtil.isNotEmpty(originalHitchDetail.getHitchStatus())) {
            hitchLogExcel.setHitchStatus(PublicZdCacheLoadImpl.getDictMc("GJZT", originalHitchDetail.getHitchStatus(), false));
            } else {
            hitchLogExcel.setHitchStatus("");
            }
            if (StringUtil.isNotEmpty(originalHitchDetail.getCheckoutResult())) {
            hitchLogExcel.setCheckoutResult(PublicZdCacheLoadImpl.getDictMc("YZXJY", originalHitchDetail.getCheckoutResult(), false));
            } else {
            hitchLogExcel.setCheckoutResult("");
            }
            list.add(hitchLogExcel);
        }
        try {
            path=filepath+"/"+ ComDateUtils.getDate() + TokenUtils.getRandom() + ".xlsx";
            ExcelUtil.writeToFile(list, null, path);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return path;
}

需要转换的excel对象:

public class HitchLogExcel {
/**
*档号 
*/
@Excel(name = "档号", width = 20,length = 50)
private  String fileNum;
/**
*著录题名 
*/
@Excel(name = "著录题名", width = 20,length = 50)
private String  recordTitle;
/**
*著录页数 
*/
@Excel(name = "著录页数", width = 20,length = 50)
private String recordPageNum;
/**
* 文件页数
*/
@Excel(name = "文件页数", width = 20,length = 50)
private String originalNum;
/**
*匹配状态 
*/
@Excel(name = "匹配状态", width = 20,length = 50)
private String matchStatus;
/**
* 挂接状态
*/
@Excel(name = "挂接状态", width = 20,length = 50)
private String hitchStatus;
/**
* 一致性检验
*/
@Excel(name = "一致性检验", width = 20,length = 50)
private String checkoutResult;

getter/setter方法。。。。

 Excel注解,用以生成Excel表格文件
 
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD,ElementType.TYPE})
public @interface Excel {


    //列名
    String name() default "";


    //宽度
    int width() default 20;


    //忽略该字段
    boolean skip() default false;


    //字符长度
    int length() default 100;


    //是否必填
    boolean must() default false;


    //是否是日期
    boolean date() default false;


}

自己封装的excel导出/导入,可以根据注解导出excel.本项目一共有13个类,里面还包含了一个反射工具,一个编码工具,10分值了。下面是测试代码 public class Test { public static void main(String[] arg) throws FileNotFoundException, IOException{ testBean(); testMap(); } public static void testBean() throws FileNotFoundException, IOException{ List l = new ArrayList(); for(int i=0;i<100;i++){ l.add(new MyBean()); } //很轻松,只需要二句话就能导出excel BeanExport be = ExportExcel.BeanExport(MyBean.class); be.createBeanSheet("1月份", "1月份人员信息").addData(l); be.createBeanSheet("2月份","2月份人员信息").addData(l); be.writeFile("E:/test/bean人员信息8.xlsx"); } //如果不想用注解,还能根据MAP导出. public static void testMap () throws FileNotFoundException, IOException{ List l = new ArrayList(); l.add(new MapHeader("姓名","name",5000)); l.add(new MapHeader("年龄","age",4000)); l.add(new MapHeader("生日","birthdate",3000)); l.add(new MapHeader("地址","address",5000)); l.add(new MapHeader("双精度","d",4000)); l.add(new MapHeader("float","f",6000)); List<Map> lm = new ArrayList<Map>(); for(int i=0;i<100;i++){ Map map = new HashMap(); map.put("name","闪电球"); map.put("age",100); map.put("birthdate",new Date()); map.put("address","北京市广东省AAA号123楼!"); map.put("d",22.222d); map.put("f",295.22f); lm.add(map); } MapExport me = ExportExcel.mapExport(l); me.createMapSheel("1月份","广东省人员信息").addData(lm); me.createMapSheel("2月份", "北京市人员信息").addData(lm); me.writeFile("E:/test/map人员信息9.xlsx"); } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值