POI 实现Excel导入

什么是POI

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。

认识Excel

下图就是一个Workbook工作簿,也就是一张excel工作表。

图片描述

下图是工作簿的部分组件。
图片描述

上面的图片很清晰的说明了一个工作簿的组成,就和我们平时用的excel文档一样,而在我们用POI解析Excel文件时,每个组件都有相应的类,最主要的几个如下(创建一个新的工作簿):

(1) 一个Excel表格,就是一个Workbook工作簿类的对象。
        Workbook  workbook = new  HSSFWorkbook();
(2) 一个Sheet工作表,就是一个Sheet类的对象,通过workbook获取。
        Sheet  sheet = workbook. createSheet(“工作表名字”);  
(3) 一行,就是一个Row类的对象,通过sheet获取。
        Row  row = sheet. createRow(0);
(4) 一个单元格,就是一个Cell类的对象,通过row获取。
        Cell  cell = row.createCell((short)0);
(5)单元格格式,是一个CellStyle类的对象,通过workbook设置。
        CellStyle  style = workbook.createCellStyle(); 
(6)单元格内容格式,是一个DataFormat类的对象,通过workbook设置。
        DataFormat format= workbook.createDataFormat(); 

POI —— Excel导入数据库思路

一. 创建一个文件流

InputStream is = new FileInputStream(excelPath);

二. 通过文件流读取已有的 Workbook工作簿(一切操作excel的基础类)。

(1)Workbook book1 = new HSSFWorkbook(is);  //excel文件后缀是xls 
(2)Workbook book2 = new XSSFWorkbook(is);  //excel文件后缀是xlsx

三. 读取解析Sheet工作表,有两个方法:

(1)Sheet sheet = workbook.getSheet("Sheet1");  //通过表名读取工作表Sheet1
(2)Sheet sheet = workbook.getSheetAt(0);  //通过索引读取第一张工作表

四. 得到工作表Sheet以后再读取每一行,将每一行存入一个实体。

Row row = sheet.getRow(rowNum);  //rowNum为行号
Cell attribute = row.getCell(index);  //获取每一行的每一个字段,index为列号

比如student是一个实体,那么就将获取的每个字段依次存入这个实体的每个属性中。但存入之前首先要把Cell类的值转换成实体的属性对应类型,下面我写一个方法可以将cell转换成string类型:

    private String getValue(Cell cell) 
    {
        if (null == cell)
            return null;
        
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) 
            return String.valueOf(cell.getBooleanCellValue());
        else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
        {
            DecimalFormat format = new DecimalFormat("#.##");
            format.format(cell.getNumericCellValue());
            return format.format(cell.getNumericCellValue());
        } 
        else 
            return cell.getStringCellValue();
    }

最后,将读取的每一个字段一一存入实体,将实体更新到数据库就好了。

   例:Student student = new Student();
       student.setName(getValue(row.getCell(1)) );
       student.setPassword(getValue(row.getCell(2)) );

实现代码示例

下面的代码将一个Excel文件解析成一个List对象,可以通过List对象更新数据库表。

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.students.xl.dto.StudentDTO;

//解析Excel
public class ExcelImport {
    Logger log = Logger.getLogger(this.getClass().getName());

    public List<StudentDTO> readExcel(String filePath){
        
        List<StudentDTO> list = new ArrayList<StudentDTO>(); //返回的学生集合
        
        InputStream is = null; 
        Workbook workbook = null;
        
        if("".equals(filePath)){
            return null;
        }else{
            try {
                
                is = new FileInputStream(filePath); //创建文件流
                if("xls".equals(getPostFix(filePath))){
                    workbook = new HSSFWorkbook(is);  //xls对应的HSSFWorkbook工作簿对象
                }else if("xlsx".equals(getPostFix(filePath))){
                    workbook = new XSSFWorkbook(is);  //xlsx对应的XSSFWorkbook工作簿对象
                }else{
                    return null;
                }
                
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                log.error("[ExcelImport][readExcel]:Exception" + GetCalendar.getSysdate() + e.getMessage());
            } catch (IOException e) {
                e.printStackTrace();
                log.error("[ExcelImport][readExcel]:Exception" + GetCalendar.getSysdate() + e.getMessage());
            }
            
            //循环遍历工作簿里面的sheet表
            for(int i = 0; i < workbook.getNumberOfSheets(); i++){
                Sheet sheet = workbook.getSheetAt(i); //读取工作表
                if (sheet == null) //為空判斷
                       continue;
                
                
                for(int j = 1; j <= sheet.getLastRowNum(); j++){
                    Row row = sheet.getRow(j); //读取每行
                    if(row != null){
                        StudentDTO student = new StudentDTO();
                        //设置学生实体各属性的值
                        student.setSno(getValue(row.getCell(1)));
                        student.setStu_name(getValue(row.getCell(2)));
                        student.setStu_pass("8888");
                        student.setSex(getValue(row.getCell(3)));
                        student.setXueyuan(getValue(row.getCell(4)));
                        student.setMajor(getValue(row.getCell(5)));
                        student.setS_class(getValue(row.getCell(6)));
                        student.setPhone(getValue(row.getCell(7)));
                        list.add(student);
                    }
                }
            }
        }
        
        return list;
        
    }

    //获取文件后缀
    private String getPostFix(String path) {
        if(path == null || "".equals(path.trim())){
            return "";
        }
        
        if(path.contains(".") && path.lastIndexOf(".") != path.length() -1 ){
            return path.substring(path.lastIndexOf(".") + 1, path.length()); 
        }
        
        return "";
    }

    //转换Cell类型的值
    private String getValue(Cell cell) 
    {
        if (null == cell)
            return null;
        
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) 
            return String.valueOf(cell.getBooleanCellValue());
        else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
        {
            DecimalFormat format = new DecimalFormat("#.##");
            format.format(cell.getNumericCellValue());
            return format.format(cell.getNumericCellValue());
        } 
        else 
            return cell.getStringCellValue();
    }

}

补充:(使用workbook需要的jar包)
图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值