欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

POI---读取.xls和.xlsx文件

程序员文章站 2022-05-17 09:28:28
...

读取xlsx文件:XSSFWorkbook

public static void main(String[] args) {
		getLandNoList();
	}
	public static List<String> getLandNoList(){
		List<String> list = new ArrayList<String>();
		File file = new File("1.xlsx");
		FileInputStream stream = null;
		Workbook workbook = null;
		try {
			stream = new FileInputStream(file);
			workbook = new XSSFWorkbook(stream);
			Sheet sheet = workbook.getSheetAt(0);
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				String value = row.getCell(0).getStringCellValue()+"\t"+
						row.getCell(1).getStringCellValue()+"\t"+
						row.getCell(2).getStringCellValue()+"\t"+
						row.getCell(3).getStringCellValue()+"\t"+
						row.getCell(4).getStringCellValue()+"\t"+
						row.getCell(5).getStringCellValue();
				System.out.println(value);
				list.add(value);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}finally {
			try {
				if(null != workbook) {
					workbook.close();
				}
				if(null != stream) {
					stream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list;
	}

文件:1.xlsx的内容如下:
POI---读取.xls和.xlsx文件

程序运行结果:
POI---读取.xls和.xlsx文件

读取xls文件:只需要修改一句代码即可

workbook = new XSSFWorkbook(stream);
改成:
workbook = new HSSFWorkbook(stream);

相关标签: # poi操作Excel