導入excle ,並處理數據實現文字和圖片相對應

導入excel 處理文件,我使用的是poi 處理java

  引入依賴web

  <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>examples</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>excelant</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>excelant</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>ooxml-schemas</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>scratchpad</artifactId>
            <version>3.1.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans</artifactId>
            <version>2.6.0</version>
        </dependency>

 

package com.zeus.utils.excel;

import com.zeus.constant.AdminConstants;
import org.apache.poi.POIXMLDocumentPart;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Description excel處理工具類
 * @Author latiao
 * @Date 2019/4/7
 * @Version 1.0
 */
public class ExcelItemUtil {
    /**
     * 判斷文件是不是excle文件
     *
     * @param file
     * @return boolean
     * @methodName checkFile
     * @author latiao
     * @date 2019/4/7
     */
    public static boolean checkFile(MultipartFile file) {
        //判斷文件是否存在
        if (null == file) {
            return false;
        }
        //得到文件名
        String fileName = file.getOriginalFilename();
        //判斷文件是不是excel文件
        if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
            return false;
        }
        return true;
    }

    /**
     * 獲取全部excel文字數據
     *
     * @param file
     * @return java.util.List<java.util.Map               <               java.lang.Integer               ,               java.lang.String               [               ]>>
     * @methodName readExcel
     * @author latiao
     * @date 2019/4/7
     */
    public static List<Map<Integer, String[]>> readExcel(MultipartFile file) {
        //得到Workbook工做薄對象
        Workbook workbook = getWorkBook(file);
        //建立返回對象,把每行中的值做爲一個數組,全部行做爲一個集合返回
        List<Map<Integer, String[]>> list = new ArrayList<>();
        if (workbook != null) {
            //循環sheet
            for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
                Map<Integer, String[]> map = new HashMap<>(10);
                //得到當前sheet工做表
                Sheet sheet = workbook.getSheetAt(sheetNum);
                if (sheet == null) {
                    continue;
                }
                //得到當前sheet的開始行
                int firstRowNum = sheet.getFirstRowNum();
                //得到當前sheet的結束行
                int lastRowNum = sheet.getLastRowNum();
                //循環當前sheet除了第一行的全部行
                for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
                    //得到當前行
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        continue;
                    }
                    //得到當前行的開始列
                    int firstCellNum = row.getFirstCellNum();
                    //得到當前行的列數
                    int lastCellNum = row.getPhysicalNumberOfCells();
                    String[] cells = new String[row.getPhysicalNumberOfCells()];
                    //循環當前行
                    for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                        Cell cell = row.getCell(cellNum);
                        cells[cellNum] = getCellValue(cell);
                    }
                    map.put(rowNum, cells);
                }
                list.add(map);
            }
            try {
                if (workbook != null) {
                    workbook.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 不一樣格式的excel 獲得Workbook類型不一樣
     *
     * @param file
     * @return org.apache.poi.ss.usermodel.Workbook
     * @methodName getWorkBook
     * @author latiao
     * @date 2019/4/7
     */
    public static Workbook getWorkBook(MultipartFile file) {
        //得到文件名
        String fileName = file.getOriginalFilename();
        //建立Workbook工做薄對象,表示整個excel
        Workbook workbook = null;
        try {
            //獲取excel文件的io流
            InputStream is = file.getInputStream();
            //根據文件後綴名不一樣(xls和xlsx)得到不一樣的Workbook實現類對象
            if (fileName.endsWith("xls")) {
                //2003
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith("xlsx")) {
                //2007
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {

        }
        return workbook;
    }

    /**
     * 獲得string的數據,將全部文字都設置爲string方式讀取
     *
     * @param cell
     * @return java.lang.String
     * @methodName getCellValue
     * @author latiao
     * @date 2019/4/7
     */
    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        //把數字當成String來讀,避免出現1讀成1.0的狀況
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        //判斷數據的類型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: //數字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: //字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: //Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: //公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: //空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: //故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知類型";
                break;
        }
        return cellValue;
    }

    /**
     * 03版獲取圖片
     *
     * @param sheetNum
     * @param sheet
     * @param workbook
     * @return java.util.Map<java.lang.String               ,               org.apache.poi.ss.usermodel.PictureData>
     * @methodName getSheetPictrues03
     * @author latiao
     * @date 2019/4/7
     */
    public static Map<String, PictureData> getSheetPictrues03(int sheetNum, HSSFSheet sheet, HSSFWorkbook workbook) {
        Map<String, PictureData> sheetIndexPicMap = new HashMap<>(10);
        List<HSSFPictureData> pictures = workbook.getAllPictures();
        if (pictures.size() != 0) {
            //循環圖片
            for (HSSFShape shape : sheet.getDrawingPatriarch().getChildren()) {
                HSSFClientAnchor anchor = (HSSFClientAnchor) shape.getAnchor();
                if (shape instanceof HSSFPicture) {
                    HSSFPicture pic = (HSSFPicture) shape;
                    int pictureIndex = pic.getPictureIndex() - 1;
                    HSSFPictureData picData = pictures.get(pictureIndex);
                    //設置圖片的位置 sheet數_行數_列數
                    String picIndex = String.valueOf(sheetNum) + "_" + String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1());
                    sheetIndexPicMap.put(picIndex, picData);
                }
            }
            return sheetIndexPicMap;
        } else {
            return null;
        }
    }


    /**
     * 07格式excel獲取圖片。
     *
     * @param sheetNum
     * @param sheet
     * @param workbook
     * @return java.util.Map<java.lang.String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               org.apache.poi.ss.usermodel.PictureData>
     * @methodName getSheetPictrues07
     * @author latiao
     * @date 2019/4/7
     */
    public static Map<String, PictureData> getSheetPictrues07(int sheetNum, XSSFSheet sheet, XSSFWorkbook workbook) {
        Map<String, PictureData> sheetIndexPicMap = new HashMap<>(10);
        for (POIXMLDocumentPart dr : sheet.getRelations()) {
            if (dr instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) dr;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture pic = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = pic.getPreferredSize();
                    CTMarker ctMarker = anchor.getFrom();
                    String picIndex = String.valueOf(sheetNum) + "_" + ctMarker.getRow() + "_" + ctMarker.getCol();
                    sheetIndexPicMap.put(picIndex, pic.getPictureData());
                }
            }
        }
        return sheetIndexPicMap;
    }

    /**
     * 獲得全部圖片
     *
     * @param file
     * @return java.util.List<java.util.Map                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               <                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               java.lang.String                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               ,                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               org.apache.poi.ss.usermodel.PictureData>>
     * @methodName getAllDate
     * @author latiao
     * @date 2019/4/7
     */
    // /圖片及位置獲取
    public static List<Map<String, PictureData>> getAllDate(MultipartFile file) {
        // 建立文件
        System.out.println("讀取文件");
        // 建立流

        // 獲取文件後綴名
        String fileExt = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        // 建立Workbook
        Workbook wb = getWorkBook(file);
        // 建立sheet
        Sheet sheet = null;
        //獲取excel sheet總數
        int sheetNumbers = wb.getNumberOfSheets();
        // sheet list
        List<Map<String, PictureData>> sheetList = new ArrayList<>();
        // 循環sheet
        for (int i = 0; i < sheetNumbers; i++) {
            sheet = wb.getSheetAt(i);
            // map等待存儲excel圖片
            Map<String, PictureData> sheetIndexPicMap;
            // 判斷用07仍是03的方法獲取圖片
            if (fileExt.equals("xls")) {
                //03版本excel
                sheetIndexPicMap = getSheetPictrues03(i, (HSSFSheet) sheet, (HSSFWorkbook) wb);
            } else {
                sheetIndexPicMap = getSheetPictrues07(i, (XSSFSheet) sheet, (XSSFWorkbook) wb);
            }
            // 將當前sheet圖片map存入list
            sheetList.add(sheetIndexPicMap);
        }
        // Map map = getData(excelPath);

        return sheetList;
    }

    /**
     * 輸出圖片
     *
     * @param pic
     * @return java.lang.String
     * @methodName printImg
     * @author latiao
     * @date 2019/4/7
     */
    public static String printImg(PictureData pic) {
        // 獲取圖片格式
        String path = null;
        String url = null;
        if (pic != null) {
            String ext = pic.suggestFileExtension();
            String format = System.currentTimeMillis() + "";
            Random r = new Random();
            for (int i = 0; i < 3; i++) {
                format += r.nextInt(10);
            }
            path = AdminConstants.IMG_PATH + format + "." + ext;
            url = AdminConstants.SERVICE_PATH + format + "." + ext;
            byte[] data = pic.getData();
            FileOutputStream out = null;
            try {
                out = new FileOutputStream(path);
                out.write(data);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return url;

    }

}

而後將數據插入對象,並存入數據庫spring

 @RequestMapping("excel")
    public String insertProduct(MultipartFile file) {
        JSONObject json = new JSONObject();
        try {
            if (ExcelItemUtil.checkFile(file)) {
                //得到行數據列表,map中方單獨sheet的每一行數據 String[]表明一行的數據,放每一cell數據
                List<Map<Integer, String[]>> maps = ExcelItemUtil.readExcel(file);
                //得到圖片數據
                List<Map<String, PictureData>> allDate = ExcelItemUtil.getAllDate(file);
                //循環每個sheet
                for (int i = 0; i < maps.size(); i++) {
                    //當前sheet的文字信息
                    Map<Integer, String[]> strMap = maps.get(i);
                    //圖片信息
                    Map<String, PictureData> PicDataMap = allDate.get(i);
                    //遍歷map 得到信息
                    Object strkey[] = strMap.keySet().toArray();
                    //循環當前sheet
                    for (int j = 0; j < strMap.size(); j++) {
                        //信息cell數組
                        String[] strings = strMap.get(strkey[j]);
                        //GOODs對象
                        Goods goods = new Goods();
                        if (strings[0] != null) {
                            log.info(strings[0]);
                            goods.setGoodsId(strings[0]);

                        }
                        if (strings[1] != null) {
                            log.info(strings[1]);
                            goods.setGoodsName(strings[1]);
                        }
                        if (strings[2] != null) {
                            log.info(strings[2]);
                            goods.setTitle(strings[2]);
                        }
                        if (strings[3] != null) {
                            log.info(strings[3]);
                            goods.setModelnum(strings[3]);
                        }
                        if (strings[4] != null) {
                            log.info(strings[4]);
                            goods.setValueAdd(strings[4]);
                        }
                        if (strings[5] != null) {
                            log.info(strings[5]);
                            goods.setHotParts(strings[5]);
                        }
                        if (strings[6] != null) {
                            log.info(strings[6]);
                            goods.setPrice(new BigDecimal(strings[6]));
                        }
                        //小圖
                        List<String> smallPic = getPicture(PicDataMap, i, strkey[j], 7, 7);
                        if(smallPic.size()>0){
                            goods.setSmallPic(smallPic.get(0));
                        }
                        //信息行數
                        List<Integer> imageIds = new ArrayList<>();
                        List<String> picturePath = getPicture(PicDataMap, i, strkey[j], 8, 13);
                        if(picturePath.size()>0){
                            for (String path : picturePath) {
                                Image image = new Image();
                                image.setImgUrl(path);
                                imageMapper.insert(image);
                                imageIds.add(image.getImgId());
                            }
                        }
                        goods.setImagId(JSONArray.toJSONString(imageIds));
                        //商品介紹
                        List<String> introduction = getPicture(PicDataMap, i, strkey[j], 14, 39);
                        goods.setIntroduction(JSONArray.toJSONString(introduction));
                        //規格
                        List<String> spec = getPicture(PicDataMap, i, strkey[j], 40, 43);
                        goods.setSpec(JSONArray.toJSONString(spec));
                        log.info("goods="+goods.toString());
                        goodsMapper.insertGoodsByExcel(goods);
                    }
                }
                json.put("msg", "上傳成功");
                json.put("code", 0);

            } else {
                json.put("msg", "文件不是excle");
                json.put("code", 12003);
            }
        } catch (Exception e) {
            json.put("msg", "上傳失敗");
            json.put("code", 12002);
        }
        return json.toString();
    }

    private List<String> getPicture(Map<String, PictureData> picDataMap, Integer index, Object strkey, Integer start, Integer size) {
        List<String> list = new ArrayList<>();
        for (int i = start; i < size + 1; i++) {
            PictureData pictureData = picDataMap.get(index + "_" + strkey + "_" + i);
            if (pictureData != null) {
                String path = ExcelItemUtil.printImg(pictureData);
                list.add(path);
            }
        }
        return list;
    }
相關文章
相關標籤/搜索