gpt4 book ai didi

java - 如何在 java 中读取 Excel (.xlsx) 文件?

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:45 24 4
gpt4 key购买 nike

从给定的 .xlsx 文件,我尝试使用 Java 读取数据。

enter image description here

我读取文件的代码如下:

public static void main(String[] args) throws Exception {

FileInputStream file = new FileInputStream(new File("E:\\test1.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet test = workbook.getSheetAt(0);

student emp = new student();
Iterator<Row> itr = test.iterator();
itr.next();
while(itr.hasNext()){
Row row = itr.next();
emp.reedData(row);
System.out.println(id+","+name+","+options);
}

方法如下:

void reedData(Row row){
id= row.getCell(0).toString();
name= row.getCell(1).toString();
options= row.getCell(2).toString();
}

但是,我得到这样的输出:

1.0,X,play game
,,sing song
2.0,Y,play game
,,sing song

我希望输出看起来像这样,而不是上面的:

1.0,X,{play game,sing song}
2.0,Y,{play game,sing song}

这个问题是因为我正在合并 .xlsx 文件中的两个单元格。

有什么建议吗?提前谢谢你..

最佳答案

我是这样做的。

import static java.lang.System.out;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
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.DataFormatter;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class read {
public static void main(String [] args){
FileInputStream excelFile = new FileInputStream(new File(keep));
XSSFWorkbook wb = new XSSFWorkbook(excelFile);
XSSFSheet sheet = wb.getSheetAt(0);

int rowCount; // number of rows of newly form excel files
rowCount= sheet.getPhysicalNumberOfRows();
out.println(rowCount);

//trying to iterate the excel file
int i =0;
Iterator<Row> rowIterator = sheet.iterator();
do{
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(cell.getColumnIndex()==0) { // to read the first column
DataFormatter df = new DataFormatter();
String str2 = df.formatCellValue(cell);
customerNo.add(str2);
}
}
++i;
if(i>rowCount)break;
//break;
}while(rowIterator.hasNext());
wb.close();
}
}

希望这对您有所帮助。

关于java - 如何在 java 中读取 Excel (.xlsx) 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37811334/

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