前提:需要引入POI的jar包。

 

public class TemplateFileSheetParseVO {

/**
* 表名称
*/
private String tableName;

/**
* 列名称
*/
private List<String> columnNames;
}
private TemplateFileSheetParseVO extractContent(File file, Integer sheetIndex) throws IOException {

Workbook wb = WorkbookFactory.create(new FileInputStream(file));
try {
Sheet sheet = wb.getSheetAt(sheetIndex);
String sheetName = sheet.getSheetName();
Row headerRow = sheet.getRow(0);
if(headerRow == null){
throw new BusinessException("第" + (sheetIndex + 1) + "个sheet,不存在表头");
}
int columnCount = sheet.getRow(0).getLastCellNum();
if(columnCount <= 0){
throw new BusinessException("表头不存在");
}
List<String> headers = new ArrayList<>();

for (int i = 0; i < columnCount; i++) {
Cell cell = headerRow.getCell(i);
headers.add(cell.getStringCellValue());
}

TemplateFileSheetParseVO vo = new TemplateFileSheetParseVO();
vo.setTableName(sheetName);
vo.setColumnNames(headers);
return vo;
} catch (BusinessException e) {
throw e;
}catch (Exception e) {
log.error("", e);
throw new BusinessException("-1", e.getMessage());
} finally {
try {
if (wb != null) {
wb.close();
}
} catch (IOException e) {
log.info(e.getMessage());
}
}
}
posted on 2024-12-17 11:11  毛会懂  阅读(1)  评论(0编辑  收藏  举报