【发布时间】:2018-07-11 22:43:55
【问题描述】:
我有一个 Excel 表格,我使用 Apache POI 库来读取该表格,但我希望用户选择哪一行 &(多个选定的单元格)来显示其数据。 例如:
Name | ID | Password | date
john | 1001 | 1234 | 2-9-1997
James | 1002 |4567 | 24-6-1980
Liza | 1003 | 7890 | 18 -11-1990
我想读取第一行,但只读取名称、ID 和数据单元格,而不是所有行。我该怎么做?
这是我的尝试:
package javaapplication;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class JavaApplication {
public static void main(String[] args) {
try {
// Specify the path of file
File path=new File("/Users/monasaad1/Desktop/emp.xlsx");
// load file
FileInputStream file=new FileInputStream(path);
// load workbook
XSSFWorkbook workbook=new XSSFWorkbook(file);
// Load sheet- Here we are loading first sheetonly
XSSFSheet sheet1= workbook.getSheetAt(0);
int rowCounter = sheet1.getLastRowNum();
// user input row & cell
Scanner input = new Scanner(System.in);
System.out.print("Please choose row");
int choosenRow = input.nextInt();
System.out.print("Please choose cell");
int choosenCell = input.nextInt();
for (int i=0; i<rowCounter+1; i++){
String data =sheet1.getRow(choosenRow).getCell(choosenCell).getStringCellValue();
System.out.println("Data from Row"+i+" is "+data);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
【问题讨论】: