【发布时间】:2021-09-14 20:24:15
【问题描述】:
我想使用 Apache POI 从 excel 表中读取所有单元格值并将其存储到一维字符串数组中。是否可以逐行从 excel 中读取数据并从每个单元格中提取值?
请帮我解决这个问题。
谢谢
【问题讨论】:
标签: java apache-poi
我想使用 Apache POI 从 excel 表中读取所有单元格值并将其存储到一维字符串数组中。是否可以逐行从 excel 中读取数据并从每个单元格中提取值?
请帮我解决这个问题。
谢谢
【问题讨论】:
标签: java apache-poi
导入 org.apache.poi.hssf.usermodel.HSSFCell; 导入 org.apache.poi.hssf.usermodel.HSSFRow; 导入 org.apache.poi.hssf.usermodel.HSSFSheet; 导入 org.apache.poi.hssf.usermodel.HSSFWorkbook; 导入 org.apache.poi.poifs.filesystem.POIFSFileSystem;
公共类 ReadExcelFile {
public static void main( String [] args ) {
String fileName="C:\\temp\\testPOI.xls";
//Read an Excel File and Store in a Vector
Vector dataHolder=readExcelFile(fileName);
//Print the data read
printCellDataToConsole(dataHolder);
}
public static Vector readExcelFile(String fileName)
{
/** --Define a Vector
--Holds Vectors Of Cells
*/
Vector cellVectorHolder = new Vector();
try{
/** Creating Input Stream**/
//InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreVector.addElement(myCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void printCellDataToConsole(Vector dataHolder) {
for (int i=0;i<dataHolder.size(); i++){
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
for (int j=0; j < cellStoreVector.size();j++){
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
String stringCellValue = myCell.toString();
System.out.print(stringCellValue+"\t");
}
System.out.println();
}
}
}
【讨论】:
有一个关于 Java 世界的文档,It's POI-Fect 向您展示了这是如何实现的。
例子:
String fileName = "C:/MyExcelFile.xls"; // file we are interested in
POIFSFileSystem fileSystem = new POIFSFileSystem(new FileInputStream(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workbook.getSheetAt(0); //Get first Excel Sheet
//STRING and NUMERIC are now Enums from org.apache.poi.ss.usermodel
for (Row row : sheet) {
for (Cell cell: row) {
switch (cell.getCellTypeEnum()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t\t\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t\t");
break;
default:
}
}
System.out.println("");
}
【讨论】: