使用Easy Excel导入数据,性别为男女,数据库值为0、1
生活随笔
收集整理的這篇文章主要介紹了
使用Easy Excel导入数据,性别为男女,数据库值为0、1
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Controller控制層
@ApiOperation(value = "用戶 - 導出")@GetMapping(value = "/export")public void importOut(HttpServletResponse response) {log.info("UserController -> importOut ");userService.importOut(response);}Server層
/*** 導出用戶* @param response*/void importOut(HttpServletResponse response);ServerImpl實現(xiàn)層
/*** 導出用戶* @param response*/@Overridepublic void importOut(HttpServletResponse response){// List<UserRole> list = iUserRoleService.list(Wrappers.<UserRole>query().lambda().eq(UserRole::getUserId, detail.getId()));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);//TODO: 查角色和權(quán)限的數(shù)據(jù)后填充到模型里Long userId = item.getId();List<UserRole> userRoleList = userRoleService.list(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));// 填充角色信息// 使用TreeSet為了去除重復,并使得角色有序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);// 填充行政區(qū)域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);}表格內(nèi)容 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({"權(quán)限信息", "行政區(qū)域"})private String region;@ExcelProperty({"權(quán)限信息", "職能部門"})private String deptName;@ExcelProperty({"權(quán)限信息", "角色"})private String roleName;}性別轉(zhuǎn)換工具: 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;/*** 性別由數(shù)據(jù)庫的0/1 轉(zhuǎn)換成*/ public class SexConverter implements Converter<Integer> {@Overridepublic Class supportJavaTypeKey() {return Integer.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}@Overridepublic Integer convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return "男".equals(cellData.getStringValue()) ? 1 : 0;}@Overridepublic 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.*;/*** @author ll* excel操作工具類* @date 2020/2/5 11:06*/ public class EasyExcelUtils {private static final Logger logger = LoggerFactory.getLogger(EasyExcelUtils.class);private static final int MAX_USER_IMPORT = 1000;/*** 單sheet導出** @param response HttpServletResponse* @param list 數(shù)據(jù) list* @param fileName 導出的文件名* @param sheetName 導入文件的 sheet 名* @param model Excel 模型class對象*/public static void writeExcel(HttpServletResponse response, List<?> list,String fileName, String sheetName, Class model) {try {//表頭樣式WriteCellStyle headWriteCellStyle = new WriteCellStyle();//設置表頭居中對齊headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);//內(nèi)容樣式WriteCellStyle contentWriteCellStyle = new WriteCellStyle();//設置內(nèi)容靠左對齊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導出失敗");}}/*** 單sheet導出** @param response HttpServletResponse* @param list 數(shù)據(jù) list* @param fileName 導出的文件名* @param sheetName 導入文件的 sheet 名* @param head 表頭*/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);//內(nèi)容樣式WriteCellStyle contentWriteCellStyle = new WriteCellStyle();//設置內(nèi)容靠左對齊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導出失敗");}}/*** 導出文件時為Writer生成OutputStream** @param fileName* @param response* @return*/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("創(chuàng)建頭文件失敗");}return null;}/*** 導入:同步讀,單sheet** @param file excel文件* @param t excel導入的model對象*/public static <T> List<T> importData(MultipartFile file, Class<T> t) {List<T> userExcelList = null;// 1.excel同步讀取數(shù)據(jù)try {userExcelList = EasyExcel.read(new BufferedInputStream(file.getInputStream())).head(t).sheet().doReadSync();} catch (Exception e) {e.printStackTrace();}// 2.檢查是否大于1000條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;// 1.excel同步讀取數(shù)據(jù)try {userExcelList = EasyExcel.read(new BufferedInputStream(new FileInputStream(file))).head(t).sheet(index).doReadSync();} catch (Exception e) {e.printStackTrace();}// 2.檢查是否大于1000條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;// 1.excel同步讀取數(shù)據(jù)try {userExcelList = EasyExcel.read(new BufferedInputStream(new FileInputStream(file))).head(t).sheet(name).doReadSync();} catch (Exception e) {e.printStackTrace();}// 2.檢查是否大于1000條if (userExcelList.size() > MAX_USER_IMPORT) {}return userExcelList;}/*** 多sheet導出** @param response HttpServletResponse* @param fileName 導出的文件名*/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();}}/*** 根據(jù)Echarts的byteList以及表格相關(guān)數(shù)據(jù)生成Ecxel表* @param response* @param buffer EchartsString* @param name Excel表名* @param title sheet名稱* @param header 表頭* @param data 表數(shù)據(jù)* @param mapParamsList data數(shù)據(jù)中的字段名稱* @return* @throws IOException*/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");//設置響應內(nèi)容類型response.setContentType("text/plain");//設置文件名稱和格式response.addHeader("Content-Disposition", "attachment;filename="+genAttachmentFileName(name,"JSON_FOR_UCC_")+".xls"); //設置名稱格式,沒有中文名稱無法顯示//創(chuàng)建HSSFWorkbook對象HSSFWorkbook wb = new HSSFWorkbook();//創(chuàng)建sheet對象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);// 右邊框//寫入表格數(shù)據(jù)//在sheet中創(chuàng)建第一行寫入titleHSSFRow rowTitle = sheet1.createRow(0);// 這里是合并excel中title的列為一列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);}//在sheet中第二行寫入表頭數(shù)據(jù)HSSFRow rowheader = sheet1.createRow(1);for (int i = 0; i < header.size(); i++) {//創(chuàng)建單元格寫入數(shù)據(jù)HSSFCell cellheader = rowheader.createCell(i);cellheader.setCellStyle(style);cellheader.setCellValue(header.get(i));}//在sheet中第三行開始寫入表數(shù)據(jù)for (int i = 0; i < data.size(); i++) {//創(chuàng)建新行數(shù)據(jù)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))));}}}//根據(jù)buffer流把圖片寫入到excel中BufferedImage bufferedImage = null;ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();bufferedImage = ImageIO.read(new ByteArrayInputStream(buffer));ImageIO.write(bufferedImage, "png", byteArrayOut);//畫圖的頂級管理器,一個sheet只能獲取一個(一定要注意這點)HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();//anchor主要用于設置圖片的屬性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));//寫出excel表數(shù)據(jù)ServletOutputStream sos = response.getOutputStream();BufferedOutputStream bos = new BufferedOutputStream(sos);wb.write(bos);bos.flush();bos.close();sos.close();return null;}/*** 防止中文文件名顯示錯誤* @param cnName* @param defaultName* @return*/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;}/*** jsonArray轉(zhuǎn)List<HashMap<String,String>>* @param pics* @param mapParamsList* @return*/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;}/*** 單sheet導出-忽略某個表頭** @param response HttpServletResponse* @param list 數(shù)據(jù) list* @param fileName 導出的文件名* @param sheetName 導入文件的 sheet 名* @param model Excel 模型class對象*/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);//內(nèi)容樣式WriteCellStyle contentWriteCellStyle = new WriteCellStyle();//忽略某個表頭Set<String> excludeColumnFiledNames = new HashSet<String>();excludeColumnFiledNames.add(line);//設置內(nèi)容靠左對齊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;/*** 用戶權(quán)限*/ @Data @ToString @ApiModel("用戶角色表") @TableName("user_role") @EqualsAndHashCode(callSuper = true) public class UserRole extends MyBaseEntity {/*** 角色id*/@ApiModelProperty(value = "'用戶id'")private Long userId;/*** 角色id*/@ApiModelProperty(value = "'角色id'")private Long roleId;/*** 行政區(qū)域code*/@ApiModelProperty(value = "行政區(qū)域code")private Long regionId;/*** 部門id*/@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;/*** id*/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;/*** 角色id*/private String roleId;/*** 部門id*/private String deptId;/*** 崗位id*/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("創(chuàng)建部門")private String depts;@TableField(exist = false)private Boolean isBindWx;}總結(jié)
以上是生活随笔為你收集整理的使用Easy Excel导入数据,性别为男女,数据库值为0、1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]VC常用小知识
- 下一篇: linux cmake编译源码,linu