Spring Boot中Excel数据导入导出的高效实现
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class ExcelService {
public List<String[]> readExcel(MultipartFile file) throws Exception {
InputStream in = file.getInputStream();
Workbook workbook = WorkbookFactory.create(in);
Sheet sheet = workbook.getSheetAt(0);
List<String[]> data = new ArrayList<>();
for (Row row : sheet) {
int columnCount = row.getLastCellNum();
String[] rowData = new String[columnCount];
for (int cn=0; cn<columnCount; cn++) {
Cell cell = row.getCell(cn, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
rowData[cn] = (cell == null) ? "" : cell.toString();
}
data.add(rowData);
}
workbook.close();
return data;
}
public Workbook writeExcel(List<String[]> data) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
int rowNum = 0;
for (String[] rowData : data) {
Row row = sheet.createRow(rowNum++);
int columnNum = 0;
for (String cellData : rowData) {
Cell cell = row.createCell(columnNum++);
cell.setCellValue(cellData);
}
}
return workbook;
}
}
这个简化版的代码示例展示了如何在Spring Boot应用中读取和写入Excel数据。readExcel
方法接收一个MultipartFile
实例,并返回一个字符串数组列表,每个数组代表一个Excel行的数据。writeExcel
方法接收一个数据列表,并创建一个新的Excel工作簿。这个示例省略了异常处理和资源清理的代码,但在实际应用中应该加以处理。
评论已关闭