@SuppressWarnings("unchecked")
public static String execlParsing(String path) throws Exception{
List<String[][]> list = new ArrayList<>();
int wide=0;
Msg msg = new Msg();
msg.setCode(Satuts.RETURN.getDesc());
File file = new File(path);
String fileName = file.getName();
if (fileName.contains(".csv") || fileName.contains(".xls") || fileName.contains(".xlsx")) {
List<String> lines = FileUtils.readLines(file, "UTF-8");
if (fileName.contains(".csv")) {
// .csv文件导出
String[] split = lines.get(0).toString().split(",");
wide=split.length;
String[][] table = new String[lines.size()][split.length];
for (int i = 0; i < lines.size(); i++) {
String[] data = lines.get(i).toString().split(",");
for (int j = 0; j < data.length; j++) {
table[i][j] = data[j];
}
}
list.add(table);
} else if (fileName.contains(".xlsx") || fileName.contains(".xls")) {
{
// 解析.xlsx/.xls文件
Workbook wb = null;
int rowNumber = 0;
FileInputStream fis = new FileInputStream(file);
// 判断文件是否存在,这里需要区别
String name = fileName.substring(fileName.indexOf("."), fileName.length());
if (file.isFile() && file.exists()) {
if (name.equals(".xls")) {
wb = new HSSFWorkbook(fis);
} else {
wb = new XSSFWorkbook(fis);
}
}
// 获取到所有的sheets
int numberOfSheets = wb.getNumberOfSheets();
String[][] table = null;
for (int i = 0; i < numberOfSheets-1; i++) {
Sheet sheet = wb.getSheetAt(i);
// 获取每行
int numberOfRow = sheet.getPhysicalNumberOfRows();
if (null != sheet.getRow(i)) {
// 获取每个单元格
rowNumber = sheet.getRow(0).getPhysicalNumberOfCells();
}
wide=rowNumber;
table = new String[numberOfRow][rowNumber];
for (int j = 0; j < numberOfRow ; j++) {
Row row = sheet.getRow(j);
// 这里是为了判断没有单元格的空白格
if (null != row) {
// 获取每个单元格
for (int k = 0; k < rowNumber ; k++) {
Cell cell = row.getCell(k);
if (null != row.getCell(k)) {
int cellType=cell.getCellType();
if (cellType == 1) {
String stringCellValue = row.getCell(k).getStringCellValue();
table[j][k] = stringCellValue;
}else if (null != cell && cellType == 0) {
if (null != row.getCell(k)) {
double numericCellValue = row.getCell(k).getNumericCellValue();
table[j][k]=String.valueOf(numericCellValue);
}
}
}
}
} else {
continue;
}
}
list.add(table);
}
}
}
} else {
msg.setMsg("请选择正确的文件格式");
return GSONUtil.getGson().toJson(msg);
}
return null;
}
使用二维数组存储execl解析数据
猜你喜欢
转载自blog.csdn.net/qq_36934544/article/details/86133204
今日推荐
周排行