【测开面试题-002】java操作excel,获取两个sheet中相同id的信息

首先excel有两个sheet,分别如下:

// 第一个sheet
id    name    age
1    宋江            20
2    张三            21
3    李四            22
4    王五            23
5    朱六            24

// 第二个sheet
userId    amount
1            10000
3            90000
4            520.13
7            6000
8            36000

 

需求:第一个sheet中有用户id:1、2、3、4、5。第二个sheet中有用户id:1、3、4、7、8。

取交集,也就是在第二个sheet中取出1、3、4三组数据的信息。

 

package com.course.coke.data;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Read2 {

    public static void main(String[] args) throws IOException {

        String[] array = getUserId();
        String filePath = "/Users/poi.xls";
        HSSFSheet sheet = getSheet(filePath,1);
        if (sheet == null){
            return;
        }

        // 遍历row
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            HSSFRow row = sheet.getRow(rowNum);
            if (row==null){
                continue;
            }

// 判断sheet2中的id是否在sheet1中出现过 if (array==null){ return; }else { for (int i = 0; i <array.length ; i++) { if (getValue(row.getCell(0)).equals(array[i])){ // 遍历列cell for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) { HSSFCell cell1 = row.getCell(cellNum); if (cell1==null){ continue; } System.out.print(getValue(cell1)+ " "); } System.out.println(); } } } } } // 读取第一个sheet页中的数据 private static String[] getUserId() throws IOException{ String filePath = "/Users/poi.xls"; HSSFSheet sheet = getSheet(filePath,0); if (sheet == null){ return null; } String[] array = new String[5]; // 存储用户id // 遍历row for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) { HSSFRow row = sheet.getRow(rowNum); if (row==null){ continue; } // 取第一列的数据 HSSFCell cell = row.getCell(0); array[rowNum-1] = getValue(cell); } return array; } // 封装了,读取指定excel的第n个sheet代码,返回对应的sheet private static HSSFSheet getSheet(String filePath,int index) throws IOException { InputStream inputStream = new FileInputStream(filePath); POIFSFileSystem fs = new POIFSFileSystem(inputStream); HSSFWorkbook workbook = new HSSFWorkbook(fs); return workbook.getSheetAt(index); // 返回第n个sheet页 } private static String getValue(HSSFCell cell){ if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN){ return String.valueOf(cell.getBooleanCellValue()); }else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){ return String.valueOf(cell.getNumericCellValue()); }else { return String.valueOf(cell.getRichStringCellValue()); } } }

 

解题思路:

1.先获取第一个sheet中的所有用户id,添加到一个String类型的一维数组中(也就是遍历每行,但只取第一列)

2.获取第二个sheet中第一列的用户id,与上一步的数组元素匹配,匹配到的,循环遍历该行信息。

 

posted @ 2021-01-20 15:34  愚人李愚  阅读(308)  评论(0编辑  收藏  举报