excel文件读取,存入数据库

Excel 专栏收录该内容
1 篇文章 0 订阅

excel文件读取,导入数据库

demo

import com.demo.test.demo.entiry.Plate;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Stream3 {
    public static void main(String[] args) throws IOException, BiffException {
        readExcel();
    }


    public static void readExcel() throws BiffException, IOException {
        String pathOfXls = "C:\\aaa.xls";
        File file = new File(pathOfXls);
        //1:创建workbook
        Workbook workbook = Workbook.getWorkbook(file);
        //2:获取第一个工作表sheet
        Sheet sheet = workbook.getSheet(0);
        //3:获取数据
        System.out.println("行:" + sheet.getRows());
        System.out.println("列:" + sheet.getColumns());
        List<Plate> list = new ArrayList<>();
        //这里的i,j决定开始读取的位置
        for (int i = 5; i < sheet.getRows(); i++) {
            Plate plate = null;
            try {
            //数据赋值给实体
                Class<?> aClass = Class.forName("com.demo.test.demo.entiry.Plate");
                plate = (Plate)aClass.newInstance();
                Field[] fields = aClass.getDeclaredFields();
                for (int j = 1; j < sheet.getColumns()-1; j++) {
                    Cell cell = sheet.getCell(j, i);
                    String name = fields[j - 1].getName();
                    Method method = aClass.getMethod("set" + name.substring(0,1).toUpperCase()+ name.substring(1),String.class);
                    method.invoke(plate,cell.getContents());
                    System.out.print(cell.getContents() + " ");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            list.add(plate);
            System.out.println();
        }
        //最后一步:关闭资源
        workbook.close();
        for (Plate plate : list) {
        //这里可以根据需要存入数据库
            System.out.println("plate = " + plate);
        }

    }
    
}

}

Plate

@Data
@AllArgsConstructor
public class Plate {
    //地区
    private String name;
    private String a;
    private String b;
    private String c;
    private String d;
    private String e;
    public Plate() {
    }
}
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值