excel导出功能

package com.infosec.ztpdp.policycenter.module.audit.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.infosec.ztpdp.policycenter.common.ModuleConverter;
import com.infosec.ztpdp.policycenter.common.dbbase.page.BaseQuery;
import com.infosec.ztpdp.policycenter.common.dbbase.page.Pagination;
import com.infosec.ztpdp.policycenter.common.dbbase.page.ParamField;
import com.infosec.ztpdp.policycenter.common.jsonresult.JsonErrotCode;
import com.infosec.ztpdp.policycenter.common.jsonresult.JsonResult;
import com.infosec.ztpdp.policycenter.common.jsonresult.JsonResultUtils;
import com.infosec.ztpdp.policycenter.common.util.AuditInternationKeyConst;
import com.infosec.ztpdp.policycenter.common.util.Const;
import com.infosec.ztpdp.policycenter.common.util.DateUtil;
import com.infosec.ztpdp.policycenter.common.util.deciphering.EncryptionFactory;
import com.infosec.ztpdp.policycenter.common.validate.PatternConst;
import com.infosec.ztpdp.policycenter.common.validate.ValidatedApiParamConst;
import com.infosec.ztpdp.policycenter.common.validate.ValidatedMsgConst;
import com.infosec.ztpdp.policycenter.component.LocaleMessageSourceService;
import com.infosec.ztpdp.policycenter.module.audit.entity.ManagerOperationLogBean;
import com.infosec.ztpdp.policycenter.module.audit.service.IManagerOperationLogService;
import com.infosec.ztpdp.policycenter.module.menumanager.menuconfig.entity.ModuleLogQueryDTO;
import com.infosec.ztpdp.policycenter.module.menumanager.menuconfig.service.SysMenuService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jxl.CellView;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 
 * <p>
 * 管理员操作日志
 * </p>
 *
 * <p>
 * 版权所有:北京信安世纪科技股份有限公司 (c) 2022
 * </p>
 *
 * @author jlcui
 * @date: 2023年8月30日 下午2:14:06
 *
 */
@ApiIgnore
@Api(tags = "审计,管理操作日志")
@Validated
@RestController
@RequestMapping("/audit")
public class ManageropeLogController {

	@Resource
	private LocaleMessageSourceService localeMessageSourceService;

	@Autowired
	private IManagerOperationLogService iManagerOperationLogService;

	@Autowired
	private SysMenuService sysMenuService;

	private static Map<Integer, String> operationList;

	@ApiOperation(value = "获取管理操作日志")
	@GetMapping("/get/manageropelog")
	public JsonResult<Pagination<ManagerOperationLogBean>> page(
			@Min(value = 1, message = ValidatedMsgConst.INTEGER_MSG) @NotNull(message = ValidatedMsgConst.NULL_MSG) @ApiParam(value = "页码,"
					+ ValidatedApiParamConst.INTEGER_MSG + ","
					+ ValidatedApiParamConst.NULL_MSG, required = true) @RequestParam(value = "currentPage", required = true) Integer currentPage,
			@Min(value = 1, message = ValidatedMsgConst.INTEGER_MSG) @NotNull(message = ValidatedMsgConst.NULL_MSG) @ApiParam(value = "每页显示最大数量,"
					+ ValidatedApiParamConst.INTEGER_MSG + ","
					+ ValidatedApiParamConst.NULL_MSG, required = true) @RequestParam(value = "pageSize", required = true) Integer pageSize,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "用户姓名,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "username", required = false) String username,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "登录帐号,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "loginname", required = false) String loginname,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam("用户IP,"
					+ ValidatedApiParamConst.IP_MSG) @RequestParam(value = "userip", required = false) String userip,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "功能模块,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "module", required = false) String module,
			@Length(max = 30000, message = ValidatedMsgConst.LENGTH_LIMIT_THIRTY_THOUSAND_MSG) @ApiParam(value = "详细信息,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_THIRTY_THOUSAND_MSG) @RequestParam(value = "details", required = false) String details,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "操作,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "operation", required = false) String operation,
			@Pattern(regexp = PatternConst.DATE_PATTERN_PN, message = ValidatedMsgConst.DATE_MSG) @ApiParam(value = "起始时间,"
					+ ValidatedApiParamConst.DATE_MSG) @RequestParam(value = "fromDate", required = false) String fromDate,
			@Pattern(regexp = PatternConst.DATE_PATTERN_PN, message = ValidatedMsgConst.DATE_MSG) @ApiParam(value = "结束时间,"
					+ ValidatedApiParamConst.DATE_MSG) @RequestParam(value = "endDate", required = false) String endDate,
			HttpServletRequest request) {
		JsonResult<Pagination<ManagerOperationLogBean>> jsonResult = JsonResultUtils.getFailObj();
		try {
			Pagination<ManagerOperationLogBean> pagination = new Pagination<ManagerOperationLogBean>(currentPage,
					pageSize);
			BaseQuery query = new BaseQuery();

			if (!StringUtils.isEmpty(details)) {
				details = details.replaceAll("%", "%");
				details = details.replaceAll("'", "'");
				details = URLDecoder.decode(details, "utf-8");
				query.addParamFiled("details", ParamField.LIKE, details);
			}
			if (!StringUtils.isEmpty(username)) {
				query.addParamFiled("username", ParamField.LIKE, username);
			}
			if (!StringUtils.isEmpty(loginname)) {
				query.addParamFiled("loginname", ParamField.LIKE, loginname);

			}
			if (!StringUtils.isEmpty(userip)) {
				query.addParamFiled("user_ip", ParamField.LIKE, userip);
			}
			if (!StringUtils.isEmpty(module)) {
				query.addParamFiled("module", ParamField.DENGYU, module);
			}
			if (!StringUtils.isEmpty(operation)) {
				query.addParamFiled("handle_type", ParamField.DENGYU, operation);
			}
			if (!StringUtils.isEmpty(fromDate)) {
				query.addParamFiled("create_date", ParamField.DAYU_DENGYU, fromDate);
			}
			if (!StringUtils.isEmpty(endDate)) {
				query.addParamFiled("create_date", ParamField.XIAOYU_DENGYU, endDate);
			}
			query.addOrderField("id", Const.ORDER_TYPE_DESC);
			pagination.setPageSize(pageSize);
			pagination = iManagerOperationLogService.pageByParam(pagination, query);
			List<ManagerOperationLogBean> list = pagination.getList();
			if (list != null && list.size() > 0) {
				for (ManagerOperationLogBean log : list) {
					String data = getDataEncryption(log);
					if (!data.equals(log.getSignature())) {
						log.setDatacheck(false);
					} else {
						log.setDatacheck(true);
					}
				}
			}
			jsonResult.setResult(pagination);
			jsonResult.setCode(JsonErrotCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult.setMsg(localeMessageSourceService.getMessage(AuditInternationKeyConst.DEPTOPERATIONFAILED));
		}

		return jsonResult;
	}

	/**
	 * 
	 * <p>
	 * 导出管理操作日志报表
	 * </p>
	 * 
	 * @Title: exportReport
	 * @param: @param  username
	 * @param: @param  loginname
	 * @param: @param  userip
	 * @param: @param  module
	 * @param: @param  details
	 * @param: @param  operation
	 * @param: @param  fromDate
	 * @param: @param  endDate
	 * @param: @param  request
	 * @param: @param  response
	 * @param: @throws Exception
	 * @author: jlcui
	 * @date: 2023年8月30日 下午3:33:26
	 */
	@ApiIgnore
	@ApiOperation(value = "导出管理操作日志报表")
	@GetMapping("/get/manageropelog/export-report")
	public void exportReport(@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "用户姓名,"
			+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "username", required = false) String username,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "登录帐号,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "loginname", required = false) String loginname,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam("用户IP,"
					+ ValidatedApiParamConst.IP_MSG) @RequestParam(value = "userip", required = false) String userip,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "功能模块,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "module", required = false) String module,
			@Length(max = 30000, message = ValidatedMsgConst.LENGTH_LIMIT_THIRTY_THOUSAND_MSG) @ApiParam(value = "详细信息,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_THIRTY_THOUSAND_MSG) @RequestParam(value = "details", required = false) String details,
			@Length(max = 30, message = ValidatedMsgConst.LENGTH_LIMIT_MSG) @ApiParam(value = "操作,"
					+ ValidatedApiParamConst.LENGTH_LIMIT_MSG) @RequestParam(value = "operation", required = false) String operation,
			@Pattern(regexp = PatternConst.DATE_PATTERN_PN, message = ValidatedMsgConst.DATE_MSG) @ApiParam(value = "起始时间,"
					+ ValidatedApiParamConst.DATE_MSG) @RequestParam(value = "fromDate", required = false) String fromDate,
			@Pattern(regexp = PatternConst.DATE_PATTERN_PN, message = ValidatedMsgConst.DATE_MSG) @ApiParam(value = "结束时间,"
					+ ValidatedApiParamConst.DATE_MSG) @RequestParam(value = "endDate", required = false) String endDate,
			HttpServletRequest request, HttpServletResponse response) throws Exception {

		int handleType = 0;
		String allOper = "所有操作";
		if (!StringUtils.isEmpty(operation) && !allOper.equals(operation)) {
			handleType = Integer.parseInt(operation);
		}
		String allModu = "所有模块";
		if (module == null || allModu.equals(module)) {
			module = "";
		}

		BaseQuery query = new BaseQuery();

		if (!StringUtils.isEmpty(details)) {
			details = details.replaceAll("%", "%");
			details = details.replaceAll("'", "'");
			details = URLDecoder.decode(details, "utf-8");
			query.addParamFiled("details", ParamField.LIKE, details);
		}
		if (!StringUtils.isEmpty(username)) {
			query.addParamFiled("username", ParamField.LIKE, username);
		}
		if (!StringUtils.isEmpty(loginname)) {
			query.addParamFiled("loginname", ParamField.LIKE, loginname);

		}
		if (!StringUtils.isEmpty(userip)) {
			query.addParamFiled("user_ip", ParamField.LIKE, userip);
		}
		if (!StringUtils.isEmpty(module)) {
			query.addParamFiled("module", ParamField.DENGYU, module);
		}
		if (!StringUtils.isEmpty(operation)) {
			query.addParamFiled("handle_type", ParamField.DENGYU, operation);
		}
		if (!StringUtils.isEmpty(fromDate)) {
			query.addParamFiled("create_date", ParamField.DAYU_DENGYU, fromDate);
		}

		OutputStream output = null;
		try {
			response.setContentType("text/html;charset=utf-8");
			String fileName = "manageropeLog.xls";
			response.reset();
			response.setContentType("application/x-msdownload");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			output = response.getOutputStream();

			List<ManagerOperationLogBean> list = iManagerOperationLogService.findListByParam(query);
			export(output, list);

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null) {
					output.flush();
					output.close();
					output = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 * <p>
	 * 创建excel 表格
	 * </p>
	 * 
	 * @Title: export
	 * @param: @param os
	 * @param: @param vos
	 * @author: jlcui
	 * @date: 2023年8月30日 下午3:35:41
	 */
	private void export(OutputStream os, List<ManagerOperationLogBean> vos) {
		try {
			SimpleDateFormat sdf1 = DateUtil.getBjMinsFormat();
			Map<String, String> modulMap = new HashMap<String, String>();
			// 功能模块
			List<ModuleLogQueryDTO> moduleList = sysMenuService.getModuleList();
			if (!CollectionUtils.isEmpty(moduleList)) {
				for (ModuleLogQueryDTO bean : moduleList) {
					modulMap.put(bean.getModuleCode(), bean.getModuleName());
				}
			}
			// 初始化报表风格
			WritableWorkbook wbook = Workbook.createWorkbook(os);
			// 这里先判断数据是否为空,是:值创建表格的表头后返回
			if (vos != null && vos.size() > 0) {
				List<List<ManagerOperationLogBean>> partition = Lists.partition(vos, 50000);
				for (int indexs = 0; indexs < partition.size(); indexs++) {
					List<ManagerOperationLogBean> list = partition.get(indexs);
					WritableSheet wsheet = wbook.createSheet("table" + indexs, indexs);
					int cols = creatWSheetHead(wsheet);
					int rows = 0;
					Label lable;

					for (int i = 0; i < list.size(); i++) {
						cols = 0;
						rows++;
						ManagerOperationLogBean log = list.get(i);
						// 序号
						lable = new Label(cols, rows, String.valueOf(i + 1));
						wsheet.addCell(lable);
						// 用户登录名
						lable = new Label(cols + 1, rows, log.getLoginname());
						wsheet.addCell(lable);
						// 用户姓名
						lable = new Label(cols + 2, rows, log.getUsername());
						wsheet.addCell(lable);
						// 功能模块
						String moduleName = modulMap.get(list.get(i).getModule());
						lable = new Label(cols + 3, rows, moduleName);
						wsheet.addCell(lable);
						// 操作
						if (null == operationList) {
							operationList = ModuleConverter.getOperation();
						}
						String handtype = operationList.get(list.get(i).getHandleType());
						lable = new Label(cols + 4, rows, handtype);
						wsheet.addCell(lable);
						// 时间
						String dateStr = sdf1.format(list.get(i).getCreateDate());
						lable = new Label(cols + 5, rows, dateStr);
						wsheet.addCell(lable);
						// 用户ip
						lable = new Label(cols + 6, rows, list.get(i).getUserip());
						wsheet.addCell(lable);
						// 详细信息
						lable = new Label(cols + 7, rows, list.get(i).getDetails());
						wsheet.addCell(lable);
						// 访问结果
						String result = Optional.ofNullable(list.get(i).getResult()).map(x -> x == 0 ? "成功" : "失败")
								.get();
						lable = new Label(cols + 8, rows, result);
						wsheet.addCell(lable);
					}
				}
			} else {
				WritableSheet wsheet = wbook.createSheet("table", 0);
				creatWSheetHead(wsheet);
			}
			wbook.write();
			wbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private int creatWSheetHead(WritableSheet wsheet) throws WriteException {
		CellView cellView = new CellView();
		// 设置自动大小
		cellView.setAutosize(true);
		wsheet.setColumnView(2, cellView);

		WritableFont font1 = new WritableFont(WritableFont.ARIAL, 8, WritableFont.BOLD, false,
				jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
		WritableCellFormat format1 = new WritableCellFormat(font1);
		format1.setAlignment(jxl.format.Alignment.CENTRE);
		format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
		format1.setWrap(true);
		int rows = 0;
		int cols = 0;
		Label lable = null;
		lable = new Label(cols, rows, "序号");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "登录帐号");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "用户姓名");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "功能模块");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "操作");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "时间");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "用户IP");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "详细信息");
		wsheet.addCell(lable);
		cols++;
		lable = new Label(cols, rows, "访问结果");
		wsheet.addCell(lable);
		return cols;
	}

	/**
	 * 获取功能模块和操作模块信息
	 * 
	 * @param @param request
	 * @return JsonResult result moduleList operationList pageNumber
	 * @author liyy
	 * @date 2019年6月11日下午6:27:00
	 */
	@ApiOperation(value = "获取功能模块和操作模块信息")
	@GetMapping("/get/improperhandle/get-module-and-oper")
	public JsonResult<Map<String, Object>> getModuleAndOper(HttpServletRequest request) {
		JsonResult<Map<String, Object>> jsonResult = JsonResultUtils.getFailObj();
		try {
			Map<String, Object> modelMap = new HashMap<String, Object>(16);
			List<ModuleLogQueryDTO> moduleList = sysMenuService.getModuleList();
			operationList = ModuleConverter.getOperation();

			modelMap.put("moduleList", moduleList);
			modelMap.put("operationList", operationList);
			jsonResult.setResult(modelMap);
			jsonResult.setCode(JsonErrotCode.SUCCESS_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			jsonResult.setMsg(localeMessageSourceService.getMessage(AuditInternationKeyConst.DEPTOPERATIONFAILED));
		}

		return jsonResult;
	}

	// 数据加密
	public String getDataEncryption(ManagerOperationLogBean bean) {
		String dataEncryption = bean.getLoginname() + bean.getUsername() + bean.getLogcode() + bean.getUserip()
				+ bean.getDetails() + bean.getHandleType() + bean.getModule() + bean.getResult();
		return EncryptionFactory.getEncryptions(Const.AUDIT_ENCRYPTION_MODE).encrypt(dataEncryption);
	}

}

  

posted @ 2023-08-30 15:48  JLCUI  阅读(16)  评论(0编辑  收藏  举报