你的位置:首页 > Java教程

[Java教程]POI读取EXCEL(2007以上)


import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import java.util.UUID;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.xssf.usermodel.XSSFCell;import org.apache.poi.xssf.usermodel.XSSFRow;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class test {  public importExcel(){        String excelPath = null;//excel表格的文件位置    XSSFWorkbook xwb = null;//创建excel表格的工作空间    InputStream in;    try {      in = new FileInputStream(excelPath);      xwb = new XSSFWorkbook(in);    } catch (Exception e) {      // TODO Auto-generated catch block      e.printStackTrace();      System.out.println("找不到指定路径下的excel文件!");    }         //    System.out.println("该文档一共有sheet"+xwb.getNumberOfSheets()+"个");    //开始循环sheet页    for(int i=0;i<xwb.getNumberOfSheets();i++){      XSSFSheet sheet = xwb.getSheetAt(0);//读取第1个sheet      XSSFRow row;      List<String[]> userData = new ArrayList<String[]>();//用来存从excel表格中获取到的值,然后向数据库中保存      //读取系统配置sheet页      row:for(int rowIndex = 0;rowIndex < sheet.getPhysicalNumberOfRows();rowIndex++){        if((row = sheet.getRow(rowIndex)) != null){//判断该行内容不为空          String[] userRow = new String[row.getLastCellNum()];          //开始循环每一行的列          col:for(int columnIndex = row.getFirstCellNum(); columnIndex < row.getLastCellNum(); columnIndex++){            XSSFCell cell = row.getCell(columnIndex);            if(cell != null){              cell.setCellType(Cell.CELL_TYPE_STRING);              userRow[columnIndex] = cell.getStringCellValue();            }          }          userData.add(userRow);        }      }      //开始往数据库中插入数据      if(userData.size()>0){        //开始往人员表中保存数据        Persons persons = new Persons();        persons.setName(userData.get(0)[1]);        persons.setEmail(userData.get(0)[2]);        persons.setSex(userData.get(0)[3]);        persons.setAge(Integer.parseInt(userData.get(0)[4]));        personsManage.save(persons);      }    }  }}