利用poi读取excel

来源:互联网 发布:tensorflow教程 pdf 编辑:程序博客网 时间:2024/06/05 12:08
public class PoiUtil {


public static List formatCell(Row row) {


List rowValue = new ArrayList();


if (row != null) {

int columnCount = row.getPhysicalNumberOfCells();
Object value = null;
for (int j = 0; j < columnCount; j++) {
Cell cell = row.getCell(j);

if(cell != null) {
value = getValue(cell, null);
rowValue.add(value);


}else {
rowValue.add("");
}
/*Object value = getValue(cell, null);
rowValue.add(value);*/
}
}
return rowValue;
}

//获取excel每个sheet页的前两行内容
public static JSONObject formatSheel(Sheet sheet) {


int rowCount = sheet.getPhysicalNumberOfRows();
JSONObject json = new JSONObject();
json.put("sheet", sheet.getSheetName());
List title = formatCell(sheet.getRow(0));
List cell = formatCell(sheet.getRow(1));
Map<Object, Object> map = new HashMap<>();
List dataList = new ArrayList<>();
for (int i = 0; i < title.size() && i < cell.size(); i++) {
JSONObject dataJson = new JSONObject();
dataJson.put("title", title.get(i));
dataJson.put("value", cell.get(i));
dataList.add(dataJson);
}
json.put("data", dataList);
return json;
}


public static Workbook getWorkbook(FileInputStream in, String path) {
Workbook workbook = null;
List res = new ArrayList();
try {
if (path.indexOf(".xlsx") >= 0) {
workbook = new XSSFWorkbook(in);
} else {
workbook = new HSSFWorkbook(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return workbook;

}

}