我正在使用一个程序从 Excel 文件中读取值,然后返回读取的值。我尝试过使用迭代器和 for 循环,但程序没有返回工作表中的所有值。请提出建议。
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import java.io.File;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReading {
public static STring ReadExcel(String Path){
String FakeReturn = null;
try
{
FileInputStream file = new FileInputStream(new File(Path));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheetAt(0);
for(Row row:sheet)
{
Cell cell=row.getCell(0);
Cell testcell = row.getCell(1);
if(cell.getStringCellValue()!=null)
return testcell.getStringCellValue();
else
break;
}
file.close();
}
catch (Exception e)
{
System.out.println("The code carries an exception");
e.printStackTrace();
return FakeReturn;
}
return FakeReturn;
}
}
最佳答案
一旦遇到单个特定单元格值,您就会退出,因此您始终会得到一个相同的结果。
要彻底遍历工作表,在迭代行
时,您必须获取该行内单元格的迭代器
句柄。获得单个 Cell
实例的句柄后,将其值存储到 Java Collection而不仅仅是 1 个单一值。
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.getStringCellValue(); //Do something useful with me
...
编辑:
要获取特定列,请使用下面的 CellReference
:
XSSFSheet ws = wb.getSheet("Sheet1");
CellReference cellReference = new CellReference("A11");
XSSFRow row = sheet.getRow(cellReference.getRow());
if (row != null) {
XSSFCell cell = row.getCell(cellReference.getCol());
}
关于java - 使用 Apache POI API 从 Excel 文件读取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21360950/