java读取excel-poi初次使用

前言

excel的xls与xlsx通常无法直接读取,这次学习了一下用java进行读取,分享一下,希望能帮助上大家。

导入jar包

我这里选择用Meaven进行配置

		<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
         <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17-beta1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16-beta1</version>
        </dependency>

简单演示

选择一个测试文件
在这里插入图片描述
读取的演示代码如下,注意XSSFWorkbook对应xlsx,HSSFWorkbook对应xls,读取xls的话,相应的行与单元格类型也需更改

public class XlsxTest {
	public static void main(String[] args) throws IOException {  
        //获取Excel对象,即工作簿
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream("E:\\test.xlsx"));	//XSSFWorkbook对应xlsx,HSSFWorkbook对应xls

        //获取一个Sheet对象,即工作表
        XSSFSheet sheet = wb.getSheetAt(0);	//0表示第一张工作表

        //获取Row对象
        for(int i = 0;i < sheet.getPhysicalNumberOfRows();i ++){
        	XSSFRow row = sheet.getRow(i);
        	//获取单元格对象
        	for(int j = 0;j < row.getPhysicalNumberOfCells();j ++){
        		System.out.print(row.getCell(j)+"\t");
        	}
        	System.out.println();
        }

    }  
}

可以看到控制台上成功的输出了表格中的内容
在这里插入图片描述

简单封装

public class POIUtil {
	//这个方法用于返回工作簿中指定工作表的所有记录
	public static List<List<String>> read(String path,int page) throws FileNotFoundException, IOException{
		//获取工作簿,xls与xlsx需要分开处理
		Workbook wb = null;
        if (path.endsWith("xls"))
            wb = new HSSFWorkbook(new FileInputStream(path));  
        else if (path.endsWith("xlsx"))
            wb = new XSSFWorkbook(new FileInputStream(path));  
        else{ 
            System.out.println("您输入的excel格式不正确");
            return null;
        }
        
        //获取工作表
        Sheet sheet = wb.getSheetAt(page);  
        //遍历工作表中的每一行放入rows当中
        List<List<String>> rows = new ArrayList<List<String>>();
        for (Row row : sheet) {  
        	List<String> cells = new ArrayList<String>();
        	//遍历工作表中的每一个单元格放入cells当中
            for (Cell cell : row) {  
            	cells.add(cell.getStringCellValue());
            }
            rows.add(cells);
        }  
        return rows;
	}
	//测试一下封装的方法
	public static void main(String[] args) throws Exception {
		List<List<String>> rows = POIUtil.read("E:\\test.xlsx",0);
		for(List<String> row:rows){
			System.out.println(row);
		}
	}
}

这样简单封装后,只需要文件路径以及工作表索引就可以获取表格中的所有内容了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44112790/article/details/87728467