private List<Map<String, String>> readExcelData(Sheet sheet, int startRow) {
List<Map<String, String>> data = new ArrayList<>();
int maxColumns = 0;
try {
// 遍历行,找到最大的列数
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row != null && row.getLastCellNum() > maxColumns) {
maxColumns = row.getLastCellNum();
}
}
// 遍历行,读取数据
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue; // 如果行为空,跳过
}
Map<String, String> rowData = new LinkedHashMap<>();
// 遍历单元格
for (int j = 0; j < maxColumns; j++) {
Cell cell = row.getCell(j);
String cellValue = "";
if (cell != null) {
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING) {
cellValue = cell.getStringCellValue();
} else if (cellType == CellType.NUMERIC) {
cellValue = String.valueOf(cell.getNumericCellValue());
}
}
rowData.put("column" + (j + 1), cellValue);
}
// 将一行数据添加到整体数据列表中
data.add(rowData);
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
@PostMapping("/analyses/excel999999")
public AjaxResult selectByconfig(@RequestParam(required = false) Integer configId) {
System.out.println(configId);
try {
// 根据 configId 查询 ChartConfigs 对象
ChartConfigs configs = chartConfigsService.getById(configId);
if (configs == null) {
return AjaxResult.error("配置对象不存在");
}
// 构造完整的 excelurl
String templateUrl = configs.getTemplateUrl();
String serverUrl = "https://www.topcharts.cn";
String excelurl = serverUrl + templateUrl;
System.out.println(excelurl);
// 使用 Apache POI 读取 Excel 文件内容
Workbook workbook = null;
InputStream inputStream = null;
try {
URL url = new URL(excelurl);
inputStream = url.openStream();
workbook = new XSSFWorkbook(inputStream); // 使用 XSSFWorkbook 对象打开输入流
// 假设只有一个工作表
Sheet sheet = workbook.getSheetAt(0);
// 读取 Excel 数据,从第9行开始读取
List<Map<String, String>> data = readExcelData(sheet, 8); // 从第9行开始读取数据
// 返回 AjaxResult 封装的数据
return AjaxResult.success(data);
} finally {
if (workbook != null) {
workbook.close(); // 关闭工作簿
}
if (inputStream != null) {
inputStream.close(); // 关闭输入流
}
}
} catch (Exception e) {
e.printStackTrace();
String errorMsg = (e.getMessage() != null) ? e.getMessage() : "null";
return AjaxResult.error("读取 Excel 文件出现异常:" + errorMsg);
}
}
读取excel 并且填满数据返回集合
最新推荐文章于 2024-09-10 10:21:38 发布