我正在使用 apache POI 进行 excel 导入和解析。 我必须通过传递列名来获取数据。
这是我的代码
JSONObject jo = new JSONObject();
JSONArray dataCollection = new JSONArray();
JSONObject data = null;
try {
String tempCampaignFilesPath = getSessionData("userPath") + System.getProperty("file.separator") + "tempCampaignFiles";
File someFile = new File(tempCampaignFilesPath, fileName);
/* read from this file */
FileInputStream fileInputStream = new FileInputStream(someFile);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workbook.getSheet(sheetName);
int rowNum = sheet.getLastRowNum() + 1;
int colNum = sheet.getRow(0).getLastCellNum();
Row row = null;
Cell cell = null;
for (int i = 1; i < rowNum; i++) {
row = sheet.getRow(i);
data = new JSONObject();
for (int j = 0; j < colNum; j++) {
cell = row.getCell(j);
data.put(columnList.get(j), cellToString(cell));
}
dataCollection.put(data);
}
fileInputStream.close();
// someFile.delete();
jo.put("tableData", dataCollection);
} catch (Exception e) {
e.printStackTrace();
}
return jo;
有一个列索引的规定,但我怎么能通过列名来做。
请帮帮我。
最佳答案
您必须将列名转换为索引:
int colIdx = CellReference.convertColStringToIndex(letter);
CellUtil.getCell(row, colIdx)
或者如果您需要将列索引转换为字符串:
String colName = CellReference.convertNumToColString(colIdx)
关于java - 按列名获取数据 apache poi excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34291110/