1. 程式人生 > >Java匯出excel基於註解

Java匯出excel基於註解

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;


}