java - 如何从 JAVA 中的 excel 中获取列值?
问题描述
我如何将每一行和 cloumn 14 值读取到 apache poi 4 中的字符串变量中。
while (rows.hasNext()) {
Row currentRow = rows.next();
System.out.println(currentRow);
Iterator<Cell> cellsInRow = currentRow.iterator();
while(cellsInRow.hasNext()) {
Cell currentCell = cellsInRow.next();
int cellIndex = currentCell.getColumnIndex();
int columnidx = 14;
String values = currentCell.getStringValue() //how can i get the value for every row for column 14
}
}
解决方案
如果您查看文档,即 的 javadoc Row
,您会发现非常方便的getCell(int cellnum)
方法:
获取表示给定列(逻辑单元格)的单元格,从 0 开始。如果您要求一个未定义的单元格....您会得到一个
null
.
这意味着您不应该迭代所有单元格:
while (rows.hasNext()) {
Row currentRow = rows.next();
Cell cell14 = currentRow.getCell(13); // 14th cell
String value = (cell14 == null ? null : cell14.getStringCellValue());
// use value here
}
不相关,但您不应该使用迭代器while
循环。如果您使用 for-each 循环,则代码将更简单,更易于阅读,因此不要:
Iterator<Row> rows = sheet.rowIterator();
while (rows.hasNext()) {
Row currentRow = rows.next();
Iterator<Cell> cellsInRow = currentRow.iterator();
while (cellsInRow.hasNext()) {
Cell currentCell = cellsInRow.next();
}
}
你应该使用:
for (Row currentRow : sheet) {
for (Cell currentCell : currentRow) {
}
}
看看代码改进了多少?
推荐阅读
- reactjs - React 不等待获取数据[编辑]
- arrays - 在 JSX 中访问时,对象中的嵌套数组返回“未定义”
- syntax - 将选定的答案从一个案例复制到另一个案例 SPSS
- html - 如何移动右侧表格边距旁边的滚动条
- android - 使用 MediaCodec 和 MediaMuxer 将 PCM 编码为 AAC 时没有音频
- azure-ad-b2c - 在 Azure Ad B2C 中自助密码重置需要进行 2 次电子邮件验证
- java - 无法在索引中查看 ElasticSearch 创建的文档
- swift - HackerEarth 中的 Unlucky 13 挑战
- node.js - 如何修复此错误:找不到模块“moz”Nodejs
- c# - WPF 如何在数据网格中使用行标题更改列的标题样式?