Controller控制层
@ApiOperation(value = "用户 - 导出")
@GetMapping(value = "/export")
public void importOut(HttpServletResponse response) {
log.info("UserController -> importOut ");
userService.importOut(response);
}
Server层
void importOut(HttpServletResponse response);
ServerImpl实现层
@Override
public void importOut(HttpServletResponse response){
List<User> dbUsers = this.list(new QueryWrapper<User>().eq("is_deleted",0));
EasyExcelUtils.writeExcel(response,dbUsers.stream().map(item->{
UserImportModel userImportModel = new UserImportModel();
BeanUtils.copyProperties(item, userImportModel);
Long userId = item.getId();
List<UserRole> userRoleList = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
TreeSet<String> roleNameSet = new TreeSet<String>();
for (UserRole userRole : userRoleList) {
Role role = roleService.getOne(new LambdaQueryWrapper<Role>().eq(Role::getId, userRole.getRoleId()));
if (ObjectUtil.isNotEmpty(role)) {
roleNameSet.add(role.getRoleName());
}
}
String roleName = StringUtils.join(roleNameSet.toArray(), ",");
userImportModel.setRoleName(roleName);
TreeSet<String> regionSet = new TreeSet<String>();
for (UserRole userRole : userRoleList) {
RegionOther regionOther = regionServiceOther.getOne(new LambdaQueryWrapper<RegionOther>().eq(RegionOther::getId, userRole.getRegionId()));
if (ObjectUtil.isNotEmpty(regionOther)) {
regionSet.add(regionOther.getName());
}
}
String regionName = StringUtils.join(regionSet.toArray(), ",");
userImportModel.setRegion(regionName);
TreeSet<String> deptSet = new TreeSet<String>();
for (UserRole userRole : userRoleList) {
Dept dept = deptsService.getOne(new LambdaQueryWrapper<Dept>().eq(Dept::getId, userRole.getDepartId()));
if (ObjectUtil.isNotEmpty(dept)) {
deptSet.add(dept.getDeptName());
}
}
String deptName = StringUtils.join(deptSet.toArray(), ",");
userImportModel.setDeptName(deptName);
return userImportModel;
}).collect(Collectors.toList()), "账户管理","账户信息", UserImportModel.class);
}
表格内容 UserImportModal.java
package org.springblade.modules.system.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;
import lombok.Data;
import org.springblade.common.utils.SexConverter;
import java.io.Serializable;
import java.util.Date;
@Data
@ColumnWidth(25)
@HeadRowHeight(20)
@ContentRowHeight(18)
public class UserImportModel implements Serializable {
private static final long serialVersionUID = 1L;
@ColumnWidth(15)
@ExcelProperty("账户")
private String account;
@ColumnWidth(10)
@ExcelProperty("姓名")
private String realName;
@ColumnWidth(15)
@ExcelProperty("手机号")
private String phone;
@ColumnWidth(10)
@ExcelProperty("接受短信频率")
private String frequency;
@ColumnWidth(20)
@ExcelProperty("有效期")
private Date useTime;
@ColumnWidth(20)
@ExcelProperty("生日")
private Date birthday;
@ExcelProperty("邮箱")
private String email;
@ColumnWidth(20)
@ExcelProperty(value = "性别", converter = SexConverter.class)
private Integer sex;
@ExcelProperty({
"权限信息", "行政区域"})
private String region;
@ExcelProperty({
"权限信息", "职能部门"})
private String deptName;
@ExcelProperty({
"权限信息", "角色"})
private String roleName;
}
性别转换工具: SexConverter.java
package org.springblade.common.utils;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class SexConverter implements Converter<Integer> {
@Override
public Class supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return "男".equals(cellData.getStringValue()) ? 1 : 0;
}
@Override
public CellData convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData(value.equals(1) ? "男" : "女");
}
}
工具 EasyExcelUtil.java
package org.springblade.common.utils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
public class EasyExcelUtils {
private static final Logger logger = LoggerFactory.getLogger(EasyExcelUtils.class);
private static final int MAX_USER_IMPORT = 1000;
public static void writeExcel(HttpServletResponse response, List<?> list,
String fileName, String sheetName, Class model) {
try {
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
EasyExcel.write(getOutputStream(fileName, response), model)
.excelType(ExcelTypeEnum.XLSX)
.sheet(sheetName)
.registerWriteHandler(horizontalCellStyleStrategy)
.doWrite(list);
} catch (Exception e) {
e.printStackTrace();
logger.info("excel导出失败");
}
}
public static void writeHeadExcel(HttpServletResponse response, List<?> list,
String fileName, String sheetName, List<List<String>> head) {
try {
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
EasyExcel.write(getOutputStream(fileName, response))
.excelType(ExcelTypeEnum.XLSX)
.sheet(sheetName)
.head(head)
.registerWriteHandler(horizontalCellStyleStrategy)
.doWrite(list);
} catch (Exception e) {
e.printStackTrace();
logger.info("excel导出失败");
}
}
public static OutputStream getOutputStream(String fileName, HttpServletResponse response) {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "no-store");
response.addHeader("Cache-Control", "max-age=0");
return response.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
logger.info("创建头文件失败");
}
return null;
}
public static <T> List<T> importData(MultipartFile file, Class<T> t) {
List<T> userExcelList = null;
try {
userExcelList = EasyExcel.read(new BufferedInputStream(file.getInputStream()))
.head(t)
.sheet()
.doReadSync();
} catch (Exception e) {
e.printStackTrace();
}
if (userExcelList.size() > MAX_USER_IMPORT) {
}
return userExcelList;
}
public static <T> List<T> importDataSheetIndex(File file, Class<T> t,Integer index) {
List<T> userExcelList = null;
try {
userExcelList = EasyExcel.read(new BufferedInputStream(new FileInputStream(file)))
.head(t)
.sheet(index)
.doReadSync();
} catch (Exception e) {
e.printStackTrace();
}
if (userExcelList.size() > MAX_USER_IMPORT) {
}
return userExcelList;
}
public static <T> List<T> importData2(File file, Class<T> t,String name) {
List<T> userExcelList = null;
try {
userExcelList = EasyExcel.read(new BufferedInputStream(new FileInputStream(file)))
.head(t)
.sheet(name)
.doReadSync();
} catch (Exception e) {
e.printStackTrace();
}
if (userExcelList.size() > MAX_USER_IMPORT) {
}
return userExcelList;
}
public static void writeExcelAll(HttpServletResponse response,
String fileName, List<ExcelObject> obj) throws Exception{
fileName = URLEncoder.encode(fileName, "UTF-8");
OutputStream outputStream = response.getOutputStream();
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
for(int i=0;i<obj.size();i++){
WriteSheet writeSheet1 = EasyExcel.writerSheet(i, obj.get(i).getSheetName()).head(obj.get(0).getT()).build();
excelWriter.write(obj.get(i).getData(), writeSheet1);
}
excelWriter.finish();
} catch (IOException e) {
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap();
map.put("status", "failure");
map.put("message", "下载文件失败" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}finally {
outputStream.close();
}
}
public static String bufferStreamAndData2Excel (HttpServletResponse response, byte[] buffer , String name, String title, List<String> header, List<HashMap<String,Object>> data, List<String> mapParamsList) throws IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.addHeader("Content-Disposition", "attachment;filename="
+genAttachmentFileName(name,"JSON_FOR_UCC_")
+".xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet1 = wb.createSheet(title);
if (data != null && data.size() != 0) {
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
HSSFRow rowTitle = sheet1.createRow(0);
CellRangeAddress region = new CellRangeAddress(0, 0, 0, header.size()-1);
sheet1.addMergedRegion(region);
rowTitle.createCell(0).setCellValue(title);
for (int i = 0; i < header.size(); i++) {
if(i == (header.size()-1)) {
rowTitle.createCell(i);
}else {
rowTitle.createCell(i+1);
}
}
for (Cell cell : rowTitle) {
cell.setCellStyle(style);
}
HSSFRow rowheader = sheet1.createRow(1);
for (int i = 0; i < header.size(); i++) {
HSSFCell cellheader = rowheader.createCell(i);
cellheader.setCellStyle(style);
cellheader.setCellValue(header.get(i));
}
for (int i = 0; i < data.size(); i++) {
HSSFRow rowData = sheet1.createRow(i+2);
HSSFCell cellRank = rowData.createCell(0);
cellRank.setCellStyle(style);
cellRank.setCellValue(String.valueOf(i+1));
for (int j = 0; j < mapParamsList.size(); j++ ) {
HSSFCell cellData = rowData.createCell(j+1);
cellData.setCellStyle(style);
cellData.setCellValue(String.valueOf(data.get(i).get(mapParamsList.get(j))));
}
}
}
BufferedImage bufferedImage = null;
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
bufferedImage = ImageIO.read(new ByteArrayInputStream(buffer));
ImageIO.write(bufferedImage, "png", byteArrayOut);
HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
HSSFClientAnchor anchor = null;
if(header != null && header.size() !=0) {
anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) (header.size()+3), 0,(short) (header.size()+15), 18);
}else {
anchor = new HSSFClientAnchor(0, 0, 255, 255,(short) 3, 0,(short) 15, 18);
}
anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_DO_RESIZE);
patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
ServletOutputStream sos = response.getOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(sos);
wb.write(bos);
bos.flush();
bos.close();
sos.close();
return null;
}
public static String genAttachmentFileName(String cnName,String defaultName){
try {
cnName = new String (cnName.getBytes("GB2312"),"ISO-8859-1");
} catch (Exception e) {
e.printStackTrace();
cnName = defaultName;
}
return cnName;
}
public static List<HashMap<String,Object>> getPics(String pics,List<String> mapParamsList) {
List<HashMap<String,Object>> res = new ArrayList<>();
if(pics==null||pics.equals("")||!pics.startsWith("[")||!pics.endsWith("]")){
return res;
}
JSONArray jsons = JSONArray.parseArray(pics);
JSONObject json = null;
HashMap<String,Object> map = null;
Object data = null;
for(int i=0;i<jsons.size();i++){
json = jsons.getJSONObject(i);
map = new HashMap<String,Object>();
for (int j=0;j<mapParamsList.size();j++) {
data = json.get((String)mapParamsList.get(j));
if(data!=null&&!"".equals(data)) {
map.put((String)mapParamsList.get(j),data);
}
}
res.add(map);
}
return res;
}
public static void writeExcelWithoutLine(HttpServletResponse response, List<?> list,
String fileName, String sheetName, Class model, String line) {
try {
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
Set<String> excludeColumnFiledNames = new HashSet<String>();
excludeColumnFiledNames.add(line);
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
EasyExcel.write(getOutputStream(fileName, response), model)
.excludeColumnFiledNames(excludeColumnFiledNames)
.excelType(ExcelTypeEnum.XLSX)
.sheet(sheetName)
.registerWriteHandler(horizontalCellStyleStrategy)
.doWrite(list);
} catch (Exception e) {
e.printStackTrace();
logger.info("excel导出失败");
}
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class ExcelObject{
private String sheetName;
private List<?> data;
private Class T;
}
实体类 UserRole.java
package org.springblade.modules.userrole.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springblade.common.bean.MyBaseEntity;
import javax.validation.constraints.Size;
@Data
@ToString
@ApiModel("用户角色表")
@TableName("user_role")
@EqualsAndHashCode(callSuper = true)
public class UserRole extends MyBaseEntity {
@ApiModelProperty(value = "'用户id'")
private Long userId;
@ApiModelProperty(value = "'角色id'")
private Long roleId;
@ApiModelProperty(value = "行政区域code")
private Long regionId;
@ApiModelProperty(value = "部门id")
private Long departId;
}
实体类User.java
package org.springblade.modules.system.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springblade.core.tenant.mp.TenantEntity;
import org.springblade.modules.userrole.entity.UserRole;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
import java.util.List;
@Data
@TableName("blade_user")
@EqualsAndHashCode(callSuper = true)
public class User extends TenantEntity {
private static final long serialVersionUID = 1L;
private Long id;
private String frequency;
private String wx;
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date useTime;
private String code;
private Integer userType;
private String account;
private String password;
private String name;
private String realName;
private String avatar;
private String email;
private String phone;
private Date birthday;
private Integer sex;
private String roleId;
private String deptId;
private String postId;
@TableField(exist = false)
private List<UserRole> params;
@TableField(exist = false)
private List<Role> roles;
@TableField(exist = false)
private String oldPassword;
@TableField(exist = false)
private String newPassword;
@ApiModelProperty("创建部门")
private String depts;
@TableField(exist = false)
private Boolean isBindWx;
}