Reputation: 145
From a given .xlsx
file, I am trying to read data using Java.
My code for reading the file is as follows:
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);
}
The method is as follows:
void reedData(Row row){
id= row.getCell(0).toString();
name= row.getCell(1).toString();
options= row.getCell(2).toString();
}
But, I am getting output like this:
1.0,X,play game
,,sing song
2.0,Y,play game
,,sing song
Instead of the above, I want the output to look like this:
1.0,X,{play game,sing song}
2.0,Y,{play game,sing song}
This problem is because I am merging two cells in .xlsx
file.
Any suggestion? thank you in advance..
Upvotes: 5
Views: 10466
Reputation: 91
This is how I did it.
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();
}
}
hope this helps.
Upvotes: 4
Reputation: 985
It looks like you are using Apache POI. Try merging these 2 cells in your code with:
test.addMergedRegion(1,2,0,0);
or:
sheet.addMergedRegion(new CellRangeAddress(1,2,0,0))
Upvotes: 0