導入maven座標
<!-- Excel解析工具類 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>${poi.version}</version>
</dependency>
struts屬性驅動接收上傳文件
// 接收上傳文件
private File file;
public void setFile(File file) {
this.file = file;
}
具體實現
// 批量區域數據導入
public String batchImport() throws IOException {
List list = new ArrayList();
// 編寫解析代碼邏輯
// 基於.xls 格式解析 HSSF
// 1、 加載Excel文件對象
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
// 2、 讀取一個sheet
HSSFSheet sheet = hssfWorkbook.getSheetAt(0);
// 3、 讀取sheet中每一行
for (Row row : sheet) {
// 一行數據 對應 一個區域對象
if (row.getRowNum() == 0) {
// 第一行 跳過
continue;
}
// 跳過空行
if (row.getCell(0) == null
|| StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
continue;
}
list .add(row.getCell(0));
list .add(row.getCell(1));
}
}