上传带图片的Excel功能

上传带图片的Excel功能

一、上传Excel模板

上传带图片的Excel功能_第1张图片

需要的导入的jar包

        
        
            org.apache.poi
            poi
            4.0.1
         
        
            org.apache.poi
            poi-ooxml
            4.0.1
        
        
        
            org.apache.poi
            poi-ooxml-schemas
            4.0.1
        
        
        
            org.springframework
            spring-mock
            2.0.8
        
        
            org.springframework
            spring-test
            5.2.5.RELEASE
        

二、控制层

    /**
    *@Author songmo
    *@Date 2020/4/27 15:51
    *@Description 批量导入人员信息-返回失败的人员信息
    */
    @ApiOperation(value = "批量导入人员信息", notes = "")
    @PostMapping("/importPerson")
    @Log(action = "批量导入人员信息")
    public ResponseInfo importPerson(MultipartFile file) {
        List personVos = pictureService.importPerson(file);
        return ResponseInfo.success(personVos);
    }

三、service层

List importPerson(MultipartFile file);

四、impl层


    @Override
    public List importPerson(MultipartFile file) {
        //判断当前文件后缀名是否以xlsx结尾的
        String fileName = file.getOriginalFilename().toString();
        if (!StringUtils.isNotBlank(fileName)) {
            throw new ErrorCodeException("请上传需要导入的Excel文件");
        }
        int excelType = file.getOriginalFilename().lastIndexOf(".");
        String excelTypeStr = file.getOriginalFilename().substring(excelType);
        if (!excelTypeStr.equalsIgnoreCase(".xlsx")) {
            throw new ErrorCodeException("请上传以.xlsx结尾的文件");
        }
        //文件上传的路径
        String filePath = file(file);
        System.out.println(filePath);
        //返回导入失败的人员数据"C:\\Users\\songmo\\Desktop\\人员模板.xlsx"
        List list = new ArrayList();
        //存放人员集合
        List listPerson = new ArrayList();
        //获取所有的内容
        Map>> sheets = null;
        try {
            sheets = ExcelUtil.readExcelToMap(filePath, urlFile);
        } catch (IOException e) {
            LOGGER.error("获取excel内容失败"+e);
        }
        Set keys = sheets.keySet();
        List steetsNames = new ArrayList<>();
        //获取所有的key ==页名称
        for (String steetsName : keys) {
            steetsNames.add(steetsName);
        }
        //遍历所有的列
        for (int i = 0; i < sheets.size(); i++) {
            //根据页名称获取页
            Map> rows = sheets.get(steetsNames.get(i));
            LOGGER.info("页名称:" + steetsNames.get(i));
            //根据所有的行 遍历
            for (int j = 1; j < rows.size(); j++) {
                Map columns = rows.get(j);
                PersonVo personVo = new PersonVo();
                personVo.setRybm(UUID.randomUUID().toString().replace("-", ""));
                //遍历当前行的所有列
                for (int k = 0; k < columns.size(); k++) {
                    //输出
                    System.out.print("\t" + columns.get(k));
                    switch (k) {
                        case 0:
                            personVo.setName(columns.get(k));
                            break;
                        case 1:
                            personVo.setOrgName(columns.get(k));
                            break;
                        case 2:
                            personVo.setPosition(columns.get(k));
                            break;
                        case 3:
                            personVo.setTel(columns.get(k));
                            break;
                        case 4:
                            personVo.setIdCard(columns.get(k));
                            break;
                        case 5:
                            personVo.setJobNo(columns.get(k));
                            break;
                        case 6:
                            personVo.setIcCard(columns.get(k));
                            break;
                        case 7:
                            personVo.setPic(UUID.randomUUID().toString().replace("-", ""));
                            personVo.setPicUrl(columns.get(k));
                            break;
                        default:
                            break;
                    }
                }
                listPerson.add(personVo);
            }
        }
        //更新数据信息
        if(listPerson.size() > 0){
            Person person =null;
            Picture picture =null;
            for (PersonVo personVo : listPerson) {
                person =new Person();
                picture =new Picture();
                //根据组织管理获取当前组织信息
                Org orgName = orgMapper.getOrgName(personVo.getOrgName());
                if(null != orgName){
                    person.setRybm(personVo.getRybm());
                    person.setName(personVo.getName());
                    person.setOrgCode(personVo.getOrgCode());
                    person.setPic(personVo.getPic());
                    person.setIdCard(personVo.getIdCard());
                    person.setIcCard(personVo.getIcCard());
                    person.setJobNo(personVo.getJobNo());
                    person.setPosition(personVo.getPosition());
                    person.setTel(personVo.getTel());
                    person.setCreateTime(String.valueOf(System.currentTimeMillis()));
                    //保存数据
                    personMapper.save(person);
                    if(null != personVo.getPic()){
                        picture.setPicCode(personVo.getPic());
                        picture.setPicUrl(personVo.getPicUrl());
                        picture.setCreateTime(String.valueOf(System.currentTimeMillis()));
                        picture.setPicType(1);
                        pictureMapper.save(picture);
                    }
                }else{
                    list.add(personVo);
                }
            }
        }
        //删除指定路径下的文件
        deleteFile(new File(urlFile+"/webapps/picture"));
        return list;
    }

    @Override
    public String file(MultipartFile file) {
        String fileName = file.getOriginalFilename().toString();
        if (!StringUtils.isNotBlank(fileName)) {
            throw new ErrorCodeException("图片上传不能为空");
        }
        //文件上传路径
        String realPath = urlFile + "/webapps/picture" + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
        File dest = new File(realPath);
        // 判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.mkdirs();
        }
        try {
            file.transferTo(dest);
            //保存文件信息
        } catch (IOException e) {
            LOGGER.error("文件上传失败:", e);
        }
        return realPath;
    }
    /**
    *@Author songmo
    *@Date 2020/4/30 16:27
    *@Description 删除文件
    */
    public void deleteFile(File file){
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
    }

五、ExcelUtil工具类

package com.songmo.song.door.common.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author songmo
 * @Date 2020/4/28 11:30
 * @Description excel 导入util
 */
public class ExcelUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);

    public static Map>> readExcelToMap(String excelFilePath, String urlFile) throws IOException {
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        // 声明所有页的集合
        Map>> mapSheet = new LinkedHashMap<>();
        wb = readExcel(excelFilePath);
        if (wb != null) {
            // 获取总页数
            int pageSize = wb.getNumberOfSheets();
            for (int i = 0; i < pageSize; i++) {
                // 声明当前页的行和列
                Map> map = new HashMap<>();
                // 获取当前页
                sheet = wb.getSheetAt(i);
                //声明当前页图片的集合
                Map pMap = null;
                //获取当前页的所有图片
                if (excelFilePath.endsWith(".xls")) {
                    //用于区分 没写方法重载
                    pMap = getPictures1((HSSFSheet) sheet);
                } else {
                    //用于区分 没写方法重载
                    pMap = getPictures2((XSSFSheet) sheet);
                }
                //获取页名称
                String sheetName = sheet.getSheetName();
                // 取当前页的最大行数-总行数
                int rowSize = sheet.getPhysicalNumberOfRows();
                // 遍历所有行
                for (int j = 0; j < rowSize; j++) {
                    // 获取第"+j+"行"
                    row = sheet.getRow(j);
                    // 获取当前页的最大列数
                    int columnSize = row.getPhysicalNumberOfCells();
                    //保证每个的列值个数都相等
                    if( j != 0 ){
                        if(columnSize != (sheet.getRow(0).getPhysicalNumberOfCells()-1)){
                            columnSize += (sheet.getRow(0).getPhysicalNumberOfCells()-1)-columnSize;
                        }
                        //如果姓名为空直接break
                        if(null == row.getCell(0)){
                            continue;
                        }
                    }
                    // 声明当前列
                    Map columnMap = new HashMap<>();
                    //列大小
                    for (int j2 = 0; j2 < columnSize; j2++) {
                        String cellValue =null;
                        if(row.getCell(j2) !=null && !"".equals(row.getCell(j2))){
                            cellValue = getCellValue(row.getCell(j2));
                        }
                        columnMap.put(j2,cellValue);
                    }
                    // 添加当前行的内容 j代表第几行 value是列的内容 意思是第几行第几列的内容
                    map.put(j, columnMap);
                }
                //解析图片并上传到服务器 进行文件上传后 返回上传地址 并根据图片所在的表格位置 赋值表格位置为 上传后的返回地址
                Object key[] = pMap.keySet().toArray();
                for (int v = 0; v < pMap.size(); v++) {
                    //获取图像数据对象
                    PictureData pic = pMap.get(key[v]);
                    //获取文件名称
                    String picName = key[v].toString();
                    //获取文件后缀名
                    String ext = pic.suggestFileExtension();
                    //图片数据
                    byte[] data = pic.getData();
                    //将图片数据转成file
                    InputStream inputStream = new ByteArrayInputStream(data);
                    String fileName = UUID.randomUUID().toString().replace("-", "") + "." + ext;
                    //原始的文件名称
                    MultipartFile file = new MockMultipartFile(picName + "." + ext, inputStream);
                    System.out.println(urlFile + fileName);
                    File dest = new File(urlFile+"/webapps/picture" + "/" + fileName);
                    // 判断文件父目录是否存在
                    if (!dest.getParentFile().exists()) {
                        dest.getParentFile().mkdirs();
                    }
                    file.transferTo(dest);
                    //解析key 并根据key 设置 某一行的某一列的 图片链接
                    String[] split = picName.split("-");
                    Integer rowIndex = Integer.parseInt(split[0].toString()), columnIndex = Integer.parseInt(split[1].toString());
                    //根据行下标 获取所有的列
                    Map columns = map.get(rowIndex);
                    //图片的上传路径
                    columns.put(columnIndex, urlFile + fileName);
                }
                // 添加当前页的所有内容
                mapSheet.put(sheetName, map);
            }
        }
        return mapSheet;
    }

    /**
    *@Author songmo
    *@Date 2020/4/29 9:21
    *@Description 读取excel内容
    */
    private static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }

        } catch (IOException e) {
            LOGGER.error("读取Excel数据失败" + e);
        }
        return wb;
    }
    public static Map getPictures1(HSSFSheet sheet) throws IOException {
        Map map = new HashMap();
        List list = sheet.getDrawingPatriarch().getChildren();
        for (HSSFShape shape : list) {

            if (shape instanceof HSSFPicture) {
                HSSFPicture picture = (HSSFPicture) shape;

                HSSFClientAnchor cAnchor = (HSSFClientAnchor) picture.getAnchor();
                PictureData pdata = picture.getPictureData();
                // 行号-列号
                String key = cAnchor.getRow1() + "-" + cAnchor.getCol1();
                map.put(key, pdata);
            }
        }
        return map;
    }

    /**
     * @Author songmo
     * @Date 2020/4/28 13:57
     * @Description xlsx 获取图片内容
     */
    public static Map getPictures2(XSSFSheet sheet) throws IOException {
        Map map = new HashMap();
        List list = sheet.getRelations();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = picture.getPreferredSize();
                    CTMarker marker = anchor.getFrom();
                    String key = marker.getRow() + "-" + marker.getCol();
                    map.put(key, picture.getPictureData());
                }
            }
        }
        return map;
    }
    public static String getCellValue(Cell cell) {
        String cellValue = "";
        // 以下是判断数据的类型
        switch (cell.getCellTypeEnum()) {
            case NUMERIC:
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    cellValue = sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cell.getNumericCellValue())).toString();
                } else {
                    DataFormatter dataFormatter = new DataFormatter();
                    cellValue = dataFormatter.formatCellValue(cell);
                }
                break;
            case STRING:
                cellValue = cell.getStringCellValue();
                break;
            case BOOLEAN:
                cellValue = cell.getBooleanCellValue() + "";
                break;
            case FORMULA:
                cellValue = cell.getCellFormula() + "";
                break;
            case BLANK:
                cellValue = "";
                break;
            case ERROR:
                cellValue = "非法字符";
                break;
            default:
                cellValue =null;
                break;
        }
        return cellValue;
    }
}

导出带图片:https://blog.csdn.net/qq_39381529/article/details/105954844

你可能感兴趣的:(java)