Java excel 导入模板数据 数据直接获取到
时间: 2024-01-15 21:04:45 浏览: 131
以下是 Java 导入 Excel 模板数据并获取数据的示例代码:
```java
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelImportDemo {
public static void main(String[] args) {
try {
// 读取 Excel 模板文件
InputStream input = new FileInputStream("template.xlsx");
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = workbook.getSheetAt(0);
// 获取数据
List<List<String>> data = new ArrayList<>();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<String> rowData = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
rowData.add(cell.getStringCellValue());
}
data.add(rowData);
}
// 输出数据
System.out.println("Excel 模板数据:");
for (List<String> rowData : data) {
for (String cellData : rowData) {
System.out.print(cellData + "\t");
}
System.out.println();
}
// 关闭输入流
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
需要注意的是,此示例代码是基于 Apache POI 库实现的,因此需要先将该库添加到项目中。可以在 Maven 中添加以下依赖项:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
阅读全文