写一个ExcelUtils类
时间: 2023-06-01 12:07:59 浏览: 154
好的,我理解你的要求了。ExcelUtils类是一个用于操作Excel文件的工具类。下面是一个简单的实现:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
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文件
public static List<List<String>> readExcel(String filePath) {
List<List<String>> dataList = new ArrayList<>();
try {
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
List<String> rowList = new ArrayList<>();
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
String cellValue = "";
if (cell != null) {
switch (cell.getCellType()) {
case STRING:
cellValue = cell.getStringCellValue();
break;
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
break;
}
}
rowList.add(cellValue);
}
dataList.add(rowList);
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
// 写入Excel文件
public static void writeExcel(String filePath, List<List<String>> dataList) {
try {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
for (int i = 0; i < dataList.size(); i++) {
List<String> rowList = dataList.get(i);
Row row = sheet.createRow(i);
for (int j = 0; j < rowList.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowList.get(j));
}
}
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
这个ExcelUtils类提供两个方法:readExcel和writeExcel,分别用于读取和写入Excel文件。你可以调用这些方法来读取和写入Excel文件,也可以按照你的需求对这个类进行扩展和优化。
希望这个回答能够满足你的需求。如果有任何问题,请随时提出。
阅读全文