java 如何使用模板导入excel数据
时间: 2023-11-19 10:05:07 浏览: 135
java导出数据到指定的excel模板中。+Excel-template-exportJava实用源码整理learns
Java可以使用Apache POI库来操作Excel文件。下面是一个使用POI库导入Excel数据的示例:
```java
import java.io.File;
import java.io.FileInputStream;
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.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("data.xlsx"));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
List<List<String>> data = new ArrayList<List<String>>();
while (rowIterator.hasNext()) {
XSSFRow row = (XSSFRow) rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
List<String> rowData = new ArrayList<String>();
while (cellIterator.hasNext()) {
XSSFCell cell = (XSSFCell) cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case NUMERIC:
rowData.add(String.valueOf(cell.getNumericCellValue()));
break;
case STRING:
rowData.add(cell.getStringCellValue());
break;
}
}
data.add(rowData);
}
file.close();
// Print the data
for (List<String> rowData : data) {
for (String value : rowData) {
System.out.print(value + "\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个示例将Excel文件中的数据读取到一个List<List<String>>对象中,可以根据需要对读取到的数据进行进一步处理。
阅读全文