当前位置: 移动技术网 > IT编程>开发语言>Java > Java POI实现将导入Excel文件的示例代码

Java POI实现将导入Excel文件的示例代码

2019年07月19日  | 移动技术网IT编程  | 我要评论

问题描述

现需要批量导入数据,数据以excel形式导入。

poi介绍

我选择使用的是apache poi。这是有apache软件基金会开放的函数库,他会提供api给java,使其可以对office文件进行读写。

我这里只需要使用其中的excel部分。

实现

首先,excel有两种格式,一种是.xls(03版),另一种是.xlsx(07版)。针对两种不同的表格格式,poi对应提供了两种接口。hssfworkbook和xssfworkbook

导入依赖

<dependency>
  <groupid>org.apache.poi</groupid>
  <artifactid>poi</artifactid>
  <version>release</version>
</dependency>
<dependency>
  <groupid>org.apache.poi</groupid>
  <artifactid>poi-ooxml</artifactid>
  <version>release</version>
</dependency>

处理版本

workbook workbook = null;
try {
  if (file.getpath().endswith("xls")) {
    system.out.println("这是2003版本");
    workbook = new xssfworkbook(new fileinputstream(file));
  } else if (file.getpath().endswith("xlsx")){
    workbook = new hssfworkbook(new fileinputstream(file));
    system.out.println("这是2007版本");
  }
      
} catch (ioexception e) {
  e.printstacktrace();
}

这里需要判断一下excel的版本,根据扩展名,用不同的类来处理文件。

获取表格数据

获取表格中的数据分为以下几步:

1.获取表格
2.获取某一行
3.获取这一行中的某个单元格

代码实现:

// 获取第一个张表
sheet sheet = workbook.getsheetat(0);
   
// 获取每行中的字段
for (int i = 0; i <= sheet.getlastrownum(); i++) {
  row row = sheet.getrow(i);  // 获取行

  // 获取单元格中的值
  string studentnum = row.getcell(0).getstringcellvalue();  
  string name = row.getcell(1).getstringcellvalue();
  string phone = row.getcell(2).getstringcellvalue();
}

持久化

获取出单元格中的数据后,最后就是用数据建立对象了。

list<student> studentlist = new arraylist<>();

for (int i = 0; i <= sheet.getlastrownum(); i++) {
  row row = sheet.getrow(i);  // 获取行

  // 获取单元格中的值
  string studentnum = row.getcell(0).getstringcellvalue();  
  string name = row.getcell(1).getstringcellvalue();
  string phone = row.getcell(2).getstringcellvalue();
  
  student student = new student();
  student.setstudentnumber(studentnum);
  student.setname(name);
  student.setphonenumber(phone);
  
  studentlist.add(student);
}

// 持久化
studentrepository.saveall(studentlist);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网