java poi 获取Excel中所有列名
下面展示一些 内联代码片
。
/**
* 获取所有列名
* @param filePath
* @return
*/
public List<String> getSheets(String filePath) {
List<String> sheetList = new ArrayList<>();
InputStream is = null;
try {
/** 验证文件是否合法 */
if (!validateExcel(filePath)) {
System.out.println(errorInfo);
return null;
}
/** 判断文件的类型,是2003还是2007 */
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(filePath)) {
isExcel2003 = false;
}
/** 调用本类提供的根据流读取的方法 */
File file = new File(filePath);
is = new FileInputStream(file);
/** 根据版本选择创建Workbook的方式 */
Workbook wb = null;
if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
if (wb != null) {
int numberOfSheets = wb.getNumberOfSheets();
if (numberOfSheets > 0) {
for (int i = 0; i < numberOfSheets; i++) {
String sheetName = wb.getSheetName(i);
sheetList.add(sheetName);
}
}
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
return sheetList;
}