java 读取excel

1.在https://mvnrepository.com/下找到jar包

<dependency>
	groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml</artifactId>
	<version>3.17</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi-ooxml-schemas</artifactId>
	<version>3.17</version>
</dependency>
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>3.17</version>
</dependency>
<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-collections4</artifactId>
	 <version>4.1</version>
</dependency>

2.使用系统提供的文件选择框进行读取文件

private void openWindowFrameReadExcel(){
	try {
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
		FileNameExtensionFilter filter = new FileNameExtensionFilter("txt", "xlsx","xls");
		fc.setFileFilter(filter);
		int returnValue = fc.showOpenDialog(null);
		if (returnValue == JFileChooser.APPROVE_OPTION) {
			FileReader fileReader = new FileReader(fc.getSelectedFile().getAbsolutePath());
			List<ImportStationEntry> list = fileReader.readFile();
		}
	} catch (Exception e) {
			e.printStackTrace();
	}
}

3.读取excel文件内容

private List<ImportStationEntry> readFileOfXlsx() throws Exception {
	List<ImportStationEntry> list = new ArrayList<ImportStationEntry>();
	// 创建输入流,读取Excel
	InputStream is = new FileInputStream(fileName);
	// jxl提供的Workbook类
	Workbook workbook = null;
	if (fileName.endsWith("xlsx")) {
		workbook = new XSSFWorkbook(is);
	} else if (fileName.endsWith("xls")) {
		workbook = new HSSFWorkbook(is);
	}
	// Excel的页签数量
	int sheet_size = workbook.getNumberOfSheets();
	for (int i = 0; i < sheet_size; i++) {
		// 每个页签创建一个Sheet对象
		Sheet sheet = workbook.getSheetAt(i);
		for (int j = sheet.getFirstRowNum(); j < sheet.getLastRowNum(); j++) {
			Row row = sheet.getRow(j);
			if (row == null || j == 0 || j == 1) {
				continue;
			}
                        // 导入文件新建实体的bean
			ImportStationEntry istationBean = new ImportStationEntry();
			for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
				Cell cellStationid = row.getCell(1);
				if (cellStationid != null && !"".equals(cellStationid.toString())) {
					istationBean.setStationId(cellStationid.toString());
				}
			}
			list.add(istationBean);
		}
	}
	return list;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值