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;
}