本地文件转BASE64|BASE64转文件|解析Excel数据转JSON对象

本地文件转BASE64|BASE64转文件|解析Excel数据转JSON对象

废话不多说,直接上代码

对应依赖:


        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poiartifactId>
            <version>3.14version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>3.14version>
        dependency>
        
        <dependency>
            <groupId>com.asposegroupId>
            <artifactId>aspose-wordsartifactId>
            <version>15.8.0version>
        dependency>

测试类:


import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.lang.reflect.Field;
import java.util.*;


public class Test {


    /**
     *测试:将文件编码为base64字符串
     */
    public static String base64Encode() throws Exception {
        // 将文件转化为输入流
        String filePath = "F:\\data.xlsx";
        File file = new File(filePath);
        InputStream inputStream = new FileInputStream(file);

        // 将InputStream转化为byte[]
        // 如果使用byte[] byte = new byte[input.available()];这种方式会出现字节码全为0的情况,原因未知
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);

        byte[] b = new byte[1000];
        int n;
        //每次从fis读1000个长度到b中,fis中读完就会返回-1
        while ((n = inputStream.read(b)) != -1)
        {
            bos.write(b, 0, n);
        }
        inputStream.close();
        bos.close();
        byte[] bytes = bos.toByteArray();

        // 进行Base64转码
        String base64Str = Base64.getEncoder().encodeToString(bytes);
        return base64Str;
    }

    /**
     * 将文件编码成的base64字符串解码为文件输入流
     */
    public static InputStream decode2ExcelFromBase64(String base64Str) throws Exception {
        byte[] byteArray = null;
        try {
            // 解码为byte数组
            byteArray = Base64.getDecoder().decode(base64Str);
        }catch (Exception e){
            throw new Exception("解码失败");
        }
        // 将byte数组转化为输入流
        InputStream inputStream = new ByteArrayInputStream(byteArray);
        return inputStream;
    }

    public static <T> List<T> parseFromExcel(InputStream inputStream, Class<T> aimClass) throws IOException, InvalidFormatException, IllegalAccessException, InstantiationException {
        List<T> result = new ArrayList<T>();
        Workbook workbook = WorkbookFactory.create(inputStream);
        Sheet sheet = workbook.getSheetAt(0);
        int lastNum = sheet.getLastRowNum();
        int firstNum = sheet.getFirstRowNum();
        for (int i = firstNum; i < lastNum+1; i++) {
            Row row = sheet.getRow(i);
            T parseObject = aimClass.newInstance();
            Field[] fields = aimClass.getDeclaredFields();
            for (int j = 0; j < fields.length; j++) {
                Field  field = fields[j];
                field.setAccessible(true);
                Class<?> type = field.getType();
                //第j列
                Cell cell = row.getCell(j);
                if (cell == null) {
                    continue;
                }
                //很重要的一行代码,如果不加,像12345这样的数字是不会给你转成String的,只会给你转成double,而且会导致cell.getStringCellValue()报错
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String cellContent = cell.getStringCellValue();
                cellContent = "".equals(cellContent) ? "0" : cellContent;
                if (type.equals(String.class)) {
                    field.set(parseObject, cellContent);
                } else if (type.equals(char.class) || type.equals(Character.class)) {
                    field.set(parseObject, cellContent.charAt(0));
                } else if (type.equals(int.class) || type.equals(Integer.class)) {
                    field.set(parseObject, Integer.parseInt(cellContent));
                } else if (type.equals(long.class) || type.equals(Long.class)) {
                    field.set(parseObject, Long.parseLong(cellContent));
                } else if (type.equals(float.class) || type.equals(Float.class)) {
                    field.set(parseObject, Float.parseFloat(cellContent));
                } else if (type.equals(double.class) || type.equals(Double.class)) {
                    field.set(parseObject, Double.parseDouble(cellContent));
                } else if (type.equals(short.class) || type.equals(Short.class)) {
                    field.set(parseObject, Short.parseShort(cellContent));
                } else if (type.equals(byte.class) || type.equals(Byte.class)) {
                    field.set(parseObject, Byte.parseByte(cellContent));
                } else if (type.equals(boolean.class) || type.equals(Boolean.class)) {
                    field.set(parseObject, Boolean.parseBoolean(cellContent));
                }
            }
            result.add(parseObject);
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
        String base64 = base64Encode();
        InputStream inputStream = decode2ExcelFromBase64(base64);
        List<S> stuList = parseFromExcel(inputStream, S.class);
        for (int i = 0; i < stuList.size(); i++) {
            System.out.println(stuList.get(i));
        }
    }
}

实体类对象:

import lombok.Data;

@Data
public class S {
    private String orderNo;
    private String nameEn;
    private String nameCn;
    private String address;
    private String tel;
    private String mob;
    private String  office;
}

import lombok.Data;依赖

<dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.16.10version>
        dependency>

文件内容:
本地文件转BASE64|BASE64转文件|解析Excel数据转JSON对象_第1张图片
运行结果:

本地文件转BASE64|BASE64转文件|解析Excel数据转JSON对象_第2张图片

你可能感兴趣的:(java,json,excel,java)