如何用java读取excel文件_如何在Java中读取Excel(.xlsx)文件?

本文介绍了一种使用Java的Apache POI库读取.xlsx文件的方法,特别是如何处理合并单元格的问题。作者在尝试读取数据时遇到了合并单元格导致的输出不正确的问题,最终通过迭代单元格和检查列索引来正确读取每个行的数据。
摘要由CSDN通过智能技术生成

从一个给定的.xlsx文件,我试图使用Java读取数据.

026b8532e9d6fde40a75d7e9a7449bd0.png

我读取文件的代码如下:

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 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 rowIterator = sheet.iterator();

do{

Row row = rowIterator.next();

Iterator 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();

}

}

希望这可以帮助.

标签:apache-poi,java,excel,android

来源: https://codeday.me/bug/20191118/2028888.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值