gpt4 book ai didi

java - 将 XLSX 行转换为字符串并添加到数组

转载 作者:太空宇宙 更新时间:2023-11-04 14:19:35 25 4
gpt4 key购买 nike

我正在尝试获取一个基本的java程序来从xlsx文件中读取数据并将每一行作为字符串放入arrayList中,稍后我将将该字符串拆分为该行。

下面是我的代码,但是我试图找出哪里出了问题,因为它似乎没有做任何事情。

List<String> text = new ArrayList<String>();

Workbook wb = WorkbookFactory.create(new File("input.xlsx"));
DataFormatter fmt = new DataFormatter();
Sheet s = wb.getSheetAt(0);

for (Row r : s) {
StringBuffer sb = new StringBuffer();
for (Cell c : r) {
if (sb.length() > 0) sb.append(" - ");
sb.append(fmt.formatCell(c));
}
text.append(sb.toString());
}

如有任何帮助,我们将不胜感激。

最佳答案

您没有读取任何单元格。请参阅此示例:

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xlsx"));

//Get the workbook instance for XLS file
XSSFWorkbook workbook = new XSSFWorkbook (file);

//Get first sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);

//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();

//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();


try {

FileInputStream file = new FileInputStream(new File("C:\\test.xls"));

//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);

//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);

//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();

//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {

Cell cell = cellIterator.next();

switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

关于java - 将 XLSX 行转换为字符串并添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27349374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com