我需要在我的java程序中读取单个单元格(例如A1)。我能够将整个内容读出到我的程序中,但我怎样才能只阅读特定的单元格呢?
import java.io.*;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class JavaApplication2
{
static void readXlsx(File inputFile)
{
try
{
// Get the workbook instance for XLSX file
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = cellIterator.next();
switch (cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
System.out.println(" ");
break;
default:
System.out.println(cell);
}
}
}
}
catch (Exception e)
{
System.err.println("Exception :" + e.getMessage());
}
}
static void readXls(File inputFile)
{
try
{
// Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell;
Row row;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
cell = cellIterator.next();
switch (cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
System.out.println(" ");
break;
default:
System.out.println(cell);
}
}
}
}
catch (FileNotFoundException e)
{
System.err.println("Exception" + e.getMessage());
}
catch (IOException e)
{
System.err.println("Exception" + e.getMessage());
}
}
public static void main(String[] args)
{
File inputFile = new File("C://users/admin/Desktop/Content.xls");
readXls(inputFile);
}
}
这就是我所做的,我正在阅读整个内容,但我需要一个特定的单元格
答案 0 :(得分:3)
您可以使用row.getCell()方法 试试这个:
Workbook workbook = WorkbookFactory.create(yourFile.getInputstream());
Sheet sheet = workbook.getSheet(0);//1,2,3
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
row.getCell(0);
row.getCell(1);
}