Java poi 的通用工具类
时间: 2023-07-03 18:06:20 浏览: 167
以下是一个基于 Apache POI 的通用工具类,可以用于读取和写入 Excel 文件。
```
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelUtils {
/**
* 读取 Excel 文件中的数据
*
* @param filePath 文件路径
* @return 读取到的数据列表
* @throws IOException
*/
public static List<List<String>> readExcel(String filePath) throws IOException {
List<List<String>> result = new ArrayList<>();
FileInputStream inputStream = new FileInputStream(new File(filePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.iterator();
List<String> rowData = new ArrayList<>();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
rowData.add(cell.getStringCellValue());
break;
case BOOLEAN:
rowData.add(String.valueOf(cell.getBooleanCellValue()));
break;
case NUMERIC:
rowData.add(String.valueOf(cell.getNumericCellValue()));
break;
default:
rowData.add("");
}
}
result.add(rowData);
}
workbook.close();
inputStream.close();
return result;
}
/**
* 将数据写入 Excel 文件
*
* @param filePath 文件路径
* @param data 要写入的数据
* @throws IOException
*/
public static void writeExcel(String filePath, List<List<String>> data) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
int rownum = 0;
for (List<String> rowData : data) {
Row row = sheet.createRow(rownum++);
int cellnum = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(cellnum++);
cell.setCellValue(cellData);
}
}
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
}
```
这个工具类包含了两个方法,`readExcel()` 方法用于读取 Excel 文件中的数据,`writeExcel()` 方法用于将数据写入到 Excel 文件中。使用时只需传入文件路径和数据即可。
阅读全文