Java 读取Excel(xlsx)的内容及图片并保存

2020-12-24  本文已影响0人  木木禾木

jar下载地址:
https://archive.apache.org/dist/poi/release/bin/

所需jar

    package com.example.testandroidx;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class TestReadFile {


    public final static String FILEPATH = "/Users/zal/Desktop/TextAndPicture.xlsx";
    public static Map<String, PictureData> picMap = new HashMap<>();

    public static void main(String[] args) {
        try {
            picMap = getPictureFromExcel(FILEPATH, 0);
            for (String key : picMap.keySet()) {
                System.out.println(key + " ~~~ " + picMap.get(key).toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("*********************************************");
        String text = readXlsx(FILEPATH);
        System.out.println("*********************************************");
        System.out.println(text);
    }

    /**
     * 获取excel(xlsx)内容
     */
    public static String readXlsx(String path) {
        StringBuilder textBuilder = new StringBuilder();
        try {
            OPCPackage pkg = OPCPackage.open(path);
            XSSFWorkbook excel = new XSSFWorkbook(pkg);
            //获取第一个sheet
            String fileName = "", colValue = "";
            int rowIndex = 0, colIndex = 0;
            XSSFSheet sheet0 = excel.getSheetAt(0);
            for (Row cells : sheet0) {
                XSSFRow row = (XSSFRow) cells;
                colIndex = 0;
                textBuilder.append(rowIndex).append("\t");
                for (Iterator<Cell> iterator = row.cellIterator(); iterator.hasNext(); ) {
                    XSSFCell cell = (XSSFCell) iterator.next();
                    //根据单元的的类型 读取相应的结果
                    if (cell.getCellType() == CellType.STRING) {
                        colValue = cell.getStringCellValue();
                    } else if (cell.getCellType() == CellType.NUMERIC) {
                        colValue = cell.getNumericCellValue() + "";
                    } else if (cell.getCellType() == CellType.FORMULA) {
                        colValue = cell.getCellFormula();
                    } else if (cell.getCellType() == CellType.FORMULA) {
                        colValue = cell.getCellFormula();
                    }
                    textBuilder.append(colValue).append("\t");
                    if (colIndex == 0) {
                        fileName = colValue;
                    }
                    saveImg(rowIndex, colIndex, fileName);
                    colIndex++;
                }
                textBuilder.append("\n");
                rowIndex++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return textBuilder.toString();
    }

    /**
     * 获取excel(xlsx)中的图片
     */
    public static Map<String, PictureData> getPictureFromExcel(String filePath, int sheetNum) throws Exception {
        FileInputStream fis = new FileInputStream(filePath);
        //创建Map
        Map<String, PictureData> map = new LinkedHashMap<>();
        //获取HSSFWorkbook对象
        XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(fis);
        //获取当前表编码所对应的表
        XSSFSheet sheet = (XSSFSheet) workbook.getSheetAt(sheetNum);
        //获取图片列表
        List<XSSFShape> list = sheet.getDrawingPatriarch().getShapes();
        //对表格进行操作i
        for (int i = 0; i < sheet.getDrawingPatriarch().getShapes().size(); i++) {
            XSSFShape shape = list.get(i);
            XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
            if (shape instanceof XSSFPicture) {
                XSSFPicture pic = (XSSFPicture) shape;
                //获取列编号
                int col = anchor.getCol2();
                XSSFPictureData picData = pic.getPictureData();
                map.put(getImgKey(i, col), picData);
            }
        }
        return map;
    }

    private static String getImgKey(int row, int col) {
        return row + ":" + col;
    }

    public static void saveImg(int row, int col, String name) {
        String filePath = "/Users/zal/Desktop/xlsxImg/" + name + ".jpeg";
        saveImg(picMap, getImgKey(row, col), filePath);
    }

    public static void saveImg(Map<String, PictureData> map, String key, String filePath) {
        PictureData picData = map.get(key);
        if (picData == null) {
            //System.out.println(key + " 无图 " + filePath);
            return;
        }
        System.out.println(key + " 有图 " + filePath);
        byte[] data = picData.getData();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath);
            out.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}


参考:
https://blog.csdn.net/qq_21137441/article/details/79226171

上一篇下一篇

猜你喜欢

热点阅读