how to read data from excel, having only one column - java

//method contains:
public Object[][] getExcelData(String excelLocation) {
Object[][] dataSet = null;
try {
file = new FileInputStream(excelLocation);
wrkbook = new XSSFWorkbook(file);
wrkbook.close();
sheet = wrkbook.getSheetAt(0);
// to get total active row count
int rowNum = sheet.getLastRowNum();
// to get total active column count
int colNum = sheet.getRow(0).getLastCellNum();
dataSet = new Object[rowNum][colNum];
for (int i = 0; i <rowNum; i++) {
XSSFRow row = sheet.getRow(i);
for (int j = 0; j <=colNum; j++) {
XSSFCell cell = row.getCell(j);
String value = String.valueOf(cell);
dataSet[i][j] = value;
}
}
return dataSet;
} catch (Exception e) {
e.printStackTrace();
}
return null;
// return null if for any exception

If you want to return the column values from the spreadsheet as a 2d array, change the signature of your method to return an array of type String[][], iterate over each row of the spreadsheet, adding the value of all of its columns to the array, and return the Array when you're done. I haven't tested this but it should be pretty close:
public static String[][] getDataSetAsArray(XSSFSheet pSheet) {
int iRowCount = pSheet.getLastRowNum();
int iColumnCount = pSheet.getRow(pSheet.getFirstRowNum()).getLastCellNum();
String[][] strDataVals = new String[iRowCount][iColumnCount];
for (int r = 0; r <= iRowCount; r++) {
XSSFRow row = pSheet.getRow(r);
for (int c = 0; c <= iColumnCount; c++) {
strDataVals[r][c] = row.getCell(c).getStringCellValue();
}
}
return strDataVals;
}

Related

Apache POI: Cannot change cell value

I have a program that takes a workbook, writes some data into it and then sets all cells on the first row to wow, using this method:
public void test(String sheetName, int columnSize) {
Row headerRow = workbook.getSheet(sheetName).getRow(0);
for (int i=0; i<columnSize; i++) {
cell.setCellValue("wow");
}
}
It is called from inside this method:
public void write(List<List<String>> rows, List<String> columns,
String sheetName, int startRow)
throws IOException {
Sheet sheet = workbook.getSheet(sheetName);
if (sheet==null) {
sheet = workbook.createSheet(sheetName);
}
if (startRow==0) {
clearWorkbook();
Row headerRow = sheet.createRow(0);
int k=0;
for(int c=0; c<columns.size(); c++) {
String column = columns.get(c);
Cell cell = headerRow.createCell(c);
cell.setCellValue(column);
}
}
int currentRow = Math.max(1, startRow);
for (int i = 0; i <rows.size(); i++) {
List<String> rowData = rows.get(i);
Row row = sheet.createRow(currentRow++);
row.setHeight((short) 2400);
for (int j=0; j<columns.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(rowData.get(j));
}
}
System.out.println("finished editing");
// Resize all columns to fit the content size
for(int z = 0; z < columns.size(); z++) {
sheet.autoSizeColumn(z);
sheet.setColumnWidth(z, Math.min(20000, sheet.getColumnWidth(z)));
}
System.out.println("finished resizing");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(workbookName);
workbook.write(fileOut);
fileOut.close();
System.out.println("closing");
test(sheetName, columns.size()); //<<--------------------------
System.out.println("closed: " + workbookFile.getAbsolutePath());
}
However it doesn't effect cells at all. What am I doing wrong?
You need to call test() before writing the workbook to FileOutputStream.

Not able to check in excel using Apache POI if specific cell as per row and column is empty in Selenium with Java

I'm trying to write data in excel while running my tests and in Excel Test Class I have written a code to check if specific row under column is empty then write data else increment the row by 1 and then check same and write data.
From another class I'm calling ExcelTest:
ExcelTest sfName = new ExcelTest("C:\\Users\\abc\\eclipse-workspace\\dgc\\src\\com\\dg\\base\\utility\\TestData.xlsx");
sfName.setCellData("Sheet1","SingleFactor Campaign",SFCampName);
ExcelTest Class
public class ExcelTest
{
public FileInputStream fis = null;
public FileOutputStream fos = null;
public XSSFWorkbook workbook = null;
public XSSFSheet sheet = null;
public XSSFRow row = null;
public XSSFCell cell = null;
String xlFilePath;
boolean isEmptyStringCell;
public ExcelTest(String xlFilePath) throws Exception
{
this.xlFilePath = xlFilePath;
fis = new FileInputStream(xlFilePath);
workbook = new XSSFWorkbook(fis);
fis.close();
}
public void setCellData(String sheetName, String colName, int rowNum, String value)
{
try
{
int col_Num = -1;
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++)
{
if(row.getCell(i).getStringCellValue().trim().equals(colName))
{
col_Num = i;
}
}
sheet.autoSizeColumn(col_Num);
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
/*row = sheet.getRow(rowNum - 1);
if(row==null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(col_Num);
if(cell == null)
cell = row.createCell(col_Num);
cell.setCellValue(value);*/
System.out.println("The cell value is "+cell.getStringCellValue());
fos = new FileOutputStream(xlFilePath);
workbook.write(fos);
fos.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
If we remove the block comment(mentioned above in code and add then comment to this code listed below then it will just write data in cell whichever is provided while calling the function.
In below code I'm starting a loop till max 7 rows and then checking if the cell contains data then increment or write data and once it writes then exit the loop.
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
isEmptyStringCell=cell.getStringCellValue().trim().isEmpty();
if (this.isEmptyStringCell)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
else
{
j=j+1;
}
}
Expected: It should write data in a row which has no cell data.
Actual: It doesn't write anything.
I've found solution for the above question and only need to change few code and now it is working as expected:
for(int j=2; j<7; j++)
{
row = sheet.getRow(j - 1);
if(row==null)
row = sheet.createRow(j - 1);
cell = row.getCell(col_Num);
//it will check if cell contains no value then create cell and set value
if(cell == null)
{
cell = row.createCell(col_Num);
cell.setCellValue(value);
break;
}
}

Apache POI - Reading excel file in 2D array - returning null values

I am trying to read Excel -2*2 matrix through Apache POI. But the first value returned by 2D array is [null,null]. Please check my code and advise for suitable corrections.
public String[][] getDataArray(String sheetName)
{
String value ="";
String[][] data = null;
int rowCount = wb.getSheet(sheetName).getLastRowNum();
int colCount = wb.getSheet(sheetName).getRow(1).getLastCellNum()-1;
data = new String[rowCount][colCount];
for(int i=1; i<=rowCount;i++)
{
Row row = wb.getSheet(sheetName).getRow(i);
for(int j=0;j<colCount;j++)
{
Cell cell = row.getCell(j);
if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
{
value = ""+cell.getStringCellValue();
}
else
{
value = cell.getStringCellValue();
}
data[i][j] = value;
}
}
return data;
}
The debug view where we can see that the first value stored in the variable data is null, null
The excel which i am trying to read. I need only the userName and password data(2*2) alone. Not the header and Run mode datas.
Of course the value in the index 0 will be null because the i starts from 1 and not 0
for (int i = 1; i <= rowCount; i++) //i starts from one
...
data[i][j] = value;
either initialize the i from 0 or do like this
data[i-1][j] = value;
public static String[][] getSheetData(final String fileName, final String workSheetName)
throws Exception {
Integer lastRow = null;
short lastCol = 0;
String[][] sheetData = null;
FileInputStream file=new FileInputStream(MettlTest.class.getClass().getResource("/" + fileName).getPath());
workbook = new XSSFWorkbook(file);
sheet = workbook.getSheet(workSheetName);
try {
XSSFRow row;
XSSFCell cell;
lastRow = sheet.getPhysicalNumberOfRows();
lastCol = sheet.getRow(1).getLastCellNum();
sheetData = new String[lastRow - 1][lastCol];
for (int r = 1; r < lastRow; r++) {
row = sheet.getRow(r);
if (row != null) {
for (int c = 0; c < lastCol; c++) {
cell = row.getCell(c);
if (cell == null) {
sheetData[r][c] = null;
} else {
sheetData[r-1][c] = new DataFormatter().formatCellValue(cell);
}
}
}
}
return sheetData;
}
catch (final Exception e) {
throw e;
}
finally {
try {
file.close();
} catch (IOException io) {
Reporter.log("Unable to close File : " + fileName);
throw io;
}
}

Reading from excel file with blank cells to 2d array

I have a following code that reads logins and passwords from xls file starting from the second row(it skips column names) and writes it into a 2d array. But it only works if the sheet doesn't have blank cells in any of the rows. What should i do to make it work with empty cells?
private static Object[][] getUsersFromXls(String sheetName) {
final File excelFile = new File("src//resources//TestData.xls");
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(excelFile);
workbook = new HSSFWorkbook(fileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
sheet = workbook.getSheet(sheetName);
final int numberOfRows = sheet.getLastRowNum();
final int numberOfColumns = sheet.getRow(0).getLastCellNum();
final String[][] xlsData = new String[numberOfRows][numberOfColumns];
String cellValue;
for (int i = 1; i <= numberOfRows; i++) {
final HSSFRow row = sheet.getRow(i);
for (int j = 0; j < numberOfColumns; j++) {
final HSSFCell cell = row.getCell(j);
final int cellType = cell.getCellType();
if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
throw new RuntimeException("Cannot process a formula. Please change field to result of formula.");
} else {
cellValue = String.valueOf(cell);
xlsData[i - 1][j] = cellValue;
}
}
}
return xlsData;
}

Excel creation with POI

I was using Apache POI 3.7 to create Excel with HSSF. It was working fine. But during load test, I realized that it is very slow. So I Googled and found I can use SXSSF. I changed my existing code to XSSF. The result was awesome.
But I stuck with a situation, autorezisecolum() is not functioning as expected. It displays large contents as #####, because the column width shrinks. I found it is a kind of a bug already raised.
Now my point is, is there any solution so that i can use SXSSF(very important for performance) with a nice output.
Note: I am using Windows 7, JDK 1.7.09 , POI-3.10.beta-2
Please help me.
Here is my code :
Main Function :
sxssfWorkbook = new SXSSFWorkbook(5);
sxssfSheet = (SXSSFSheet) sxssfWorkbook.createSheet(sheetName);
try {
// TO Write Header
//ew.writeHeaderRow(sheet, headerNames);
ew.writeHeaderRow(sxssfSheet, headerNames);
int rowNum = headerRow + 1;
for(Map.Entry<String, List<Object>> columnData : columnDataMap.entrySet()){
ew.writeNonHeaderRow(sxssfSheet, columnData.getValue(), rowNum);
rowNum++;
}
resizeXLSXColumns(sxssfSheet,rowNum-1);
sxssfWorkbook.write(outputStream);
outputStream.close();
public void writeHeaderRow(Sheet sheet, List<String> headerNames ) {
//public void writeHeaderRow(SXSSFSheet sxssfSheet, List<String> headerNames ) {
// LinkedHashMap<String,Object> mp = getFieldNames(obj);
// ArrayList<String> colNames = (ArrayList<String>) getColumnNames();
try {
XSSFCellStyle hCellStyle = getHeaderStyle();
SXSSFRow row = (SXSSFRow) sheet.createRow(headerRow);
for (int hCellInd = 0; hCellInd < headerNames.size(); hCellInd++) {
SXSSFCell cell = (SXSSFCell) row.createCell(hCellInd);
cell.setCellStyle(hCellStyle);
cell.setCellValue(headerNames.get(hCellInd));
//sheet.autoSizeColumn(hCellInd);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void writeNonHeaderRow(SXSSFSheet sxssfSheet, List<Object> rowObj, int rowIndex)
{
CreationHelper createHelper = sxssfWorkbook.getCreationHelper();
try {
SXSSFRow row = (SXSSFRow)sheet.createRow(rowIndex);
XSSFCellStyle normalStyle = getNormalStyle();
int count = 0;
for (int rCellInd = 0; rCellInd < rowObj.size(); rCellInd++) {
//Cell cell = row.createCell(rCellInd);
SXSSFCell cell = (SXSSFCell)row.createCell(rCellInd);
cell.setCellStyle(normalStyle);
Object cellData = rowObj.get(rCellInd);
if (cellData != null) {
if (cellData instanceof Double) {
cell.setCellValue((Double) cellData);
if((Double)cellData < 0){
cell.setCellStyle(getNegativeValueStyle());
}else if((Double)cellData == 0){
normalStyle.setDataFormat((short) SXSSFCell.CELL_TYPE_BLANK) ;
cell.setCellStyle(normalStyle);
}else
cell.setCellStyle(normalStyle);
} else {
//normalStyle.setDataFormat((short) HSSFCell.CELL_TYPE_BLANK);
cell.setCellType(SXSSFCell.CELL_TYPE_BLANK);
}
//sxssfSheet.autoSizeColumn();
//sxssfSheet.setColumnWidth(rCellInd, sxssfSheet.getColumnWidth(rCellInd));
//resizeXLSXColumns(sheet);
}
//autoResizeColumns(sxssfSheet);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void resizeXLSXColumns(Sheet sheet ,int rowNum){
SXSSFRow row = (SXSSFRow)sheet.getRow(rowNum);
Iterator<Cell> itr = row.cellIterator();
int max = 0;
while(itr.hasNext()){
Cell cell = itr.next();
int width = sheet.getColumnWidth(cell.getColumnIndex());
if(width > max){
max = width;
}
//sheet.setColumnWidth(cell.getColumnIndex(),max);
}
while(itr.hasNext()){
Cell cell = itr.next();
sheet.setColumnWidth(cell.getColumnIndex(),max);
}
}

Categories

Resources