The output file is created but only the first cell is written and nothing else. I tested it with system print and all the data that I want shows up in console but is not written to the worksheet.
public class excel_read_2 {
public static void main(String[] args)
{
try
{
FileInputStream file = new FileInputStream(new File("C:/Users/h.M/Desktop/20151007-110016_outgoing.xls")); //input
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("new sheet");
FileOutputStream fileOut = new FileOutputStream("C:/Users/h.M/Desktop/workbook.xls"); //output
int rowcounter = 0;
for (int rowNum = 150; rowNum < 180; rowNum++) {
Row r = sheet.getRow(rowNum);
if (r == null) {
continue;
}
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getStringCellValue());
System.out.println("The cell was a string \" " + c.getStringCellValue()+" \" ");
} else if (c.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
Row row = sheet1.createRow((short)rowcounter);
Cell cell = row.createCell(cn);
row.createCell(cn).setCellValue(c.getNumericCellValue());
System.out.println("The cell was a number " + c.getNumericCellValue());
}
}
rowcounter++;
}
wb.write(fileOut);
fileOut.close();
file.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Create the new row before you loop, then use it once per loop.
Row row = sheet1.createRow((short)rowcounter);
int lastColumn=6;
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null){
}
else if (c.getCellType() == HSSFCell.CELL_TYPE_STRING) {
Cell cell = row.createCell(cn);
cell.setCellValue(c.getStringCellValue());
Related
I can read the data of one col 0 by using below code. I need to fetch the record for duplicate value present in col 0
FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();
for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
row = (XSSFRow) spreadsheet.getRow(rowIndex);
if (row != null) {
int colIndex = 0;
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
System.out.println(cellValueMaybeNull);
}
}
}
Declare a Map and capture all the duplicates and print it later. If the list size is more than 1 then it is duplicate case scenario.
FileInputStream fis = new FileInputStream(theNewestFile);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
XSSFRow row;
String cellValueMaybeNull;
List<Cell> cells = new ArrayList<Cell>();
Map<String,List<String>> duplicateCheck = new HashMap<String,List<String>>();
for (int rowIndex = 0; rowIndex <= spreadsheet.getLastRowNum(); rowIndex++) {
row = (XSSFRow) spreadsheet.getRow(rowIndex);
if (row != null) {
int colIndex = 0;
Cell cell = row.getCell(colIndex);
if (cell != null) {
// Found column and there is value in the cell.
cellValueMaybeNull = cell.getStringCellValue();
// Do something with the cellValueMaybeNull here ...
if(duplicateCheck.get(cellValueMaybeNull) != null) {
duplicateCheck.get(cellValueMaybeNull).add(cellValueMaybeNull);
}
else {
List<String> list = new ArrayList<String>();
list.add(cellValueMaybeNull);
duplicateCheck.put(cellValueMaybeNull, list);
}
}
}
}
for(List<String> duplicateValue : duplicateCheck.values()) {
if(duplicateValue.size() > 1) {
System.out.println("Duplicate values :"+duplicateValue);
}
}
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;
}
}
Cannot iterate the full extent of rows in my XLS spreadsheet. The code {sheet.getPhysicalNumberOfRows} returns 33492 without raising exception, but there are about 43,000 rows??.
If I supply the right number manually the loop executes without complaint.
It must be simple answer but I cannot find one anywhere. can somebody help?
try {
POIFSFileSystem fs = new POIFSFileSystem(new
FileInputStream(fileLocation));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows(); //Gets => 33494
int cols = 1; // No of columns
int tmp = 0;
for (int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if (row != null) {
cell = row.getCell(0);
if (cell != null) {
System.out.println("Line number: " + r " = " + cell);
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
My code imports the excel file then put a certain column in to a textarea
I want to know how would i modify the excel file if for example i edited something on the textarea that edit should be saved on the excel file
String excelFilePath = "sample.xlsx";
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(excelFilePath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
Workbook workbook = null;
try {
workbook = new XSSFWorkbook(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
}
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
Iterator<Cell> scellIterator = nextRow.cellIterator();
cellIterator.next();
scellIterator.next();
scellIterator.next();
Cell topicsCell = cellIterator.next();
Cell topicSentimentCell =scellIterator.next();
String cellContents = topicsCell.getStringCellValue();
String scellContents = topicSentimentCell.getStringCellValue();
String[] topics = cellContents.split(";");
String[] topicSentiment = scellContents.split(";");
ArrayList<String> tpc = new ArrayList<>();
ArrayList<String> topicsents = new ArrayList<>();
for(int i = 0; i < topics.length; i++) {
topics[i] = topics[i].trim();
tpc.add(topics[i]);
for (int indx = 0; indx < tpc.size(); indx++) {
textArea.append(tpc.get(indx)+"\n");
}
}
for(int si = 0; si < topicSentiment.length; si++) {
topicSentiment[si] = topicSentiment[si].trim();
topicsents.add(topicSentiment[si]);
for (int index = 0; index < topicsents.size(); index++) {
// textArea.append(topicsents.get(index)+"\n");
System.out.print(topicsents+"\n");
}
}
}
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
Open a file as XSSFWorkbook
Open a XSSFSheet of the workbook
Make some changes in the sheet. For example change the value of a XSSFCell
Save the changes by workbook.write()
Example
// Open workbook and sheet
final XSSFWorkbook workbook = new XSSFWorkbook(new File("filename.xlsx"));
final XSSFSheet sheet = workbook.getSheetAt(0);
// Iterate rows
final int firstRowNumber = sheet.getFirstRowNum();
final int lastRowNumber = sheet.getLastRowNum();
for (int rowNumber = firstRowNumber; rowNumber < lastRowNumber; rowNumber++ ) {
final XSSFRow row = sheet.getRow(rowNumber);
if (row == null) continue;
// Iterate columns
final int firstColumnNumber = row.getFirstCellNum();
final int lastColumnNumber = row.getLastCellNum();
for (int columnNumber = firstColumnNumber; columnNumber < lastColumnNumber; columnNumber++ ) {
final XSSFCell cell = row.getCell(firstColumnNumber);
if (cell == null) continue;
// Make some changes
cell.setCellValue("new Value");
}
}
// Save changes
workbook.write(new FileOutputStream("newFilename.xlsx"));
I am facing a problem while iterating all the cells in a row, I am able to read first 4 cells properly rest all coming as null. Any help appreciated
//Below is the code I am using
InputStream is = new FileInputStream(new File(fileName));
Workbook workbook = new XSSFWorkbook(is);
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(i);
String name = sheet.getSheetName();
if (name.equals(sheetName)) {
Iterator<Row> rowItr = sheet.rowIterator();
while (rowItr.hasNext()) {
Row eachRow = rowItr.next();
QuestionObjBuilder builder = new QuestionObjBuilder();
Iterator<Cell> cellItr = eachRow.cellIterator();
int index = 1;
while (cellItr.hasNext()) {
Cell eachCell = cellItr.next();
int cellType = eachCell.getCellType();
String label = "";
if (cellType == Cell.CELL_TYPE_STRING) {
label = eachCell.getStringCellValue();
} else if (cellType == Cell.CELL_TYPE_NUMERIC) {
int value = (int) eachCell.getNumericCellValue();
label = String.valueOf(value);
}
builder = builder.set(index, label);
index++;
if (index > 10) {
break;
}
}
}
}
}
workbook.close();
If your goal is to read all cells from the excel you can use this code,
FileInputStream fileInputStream = new FileInputStream(fileName);
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet(sheetName);
Iterator<Row> it = worksheet.rowIterator();
while(it.hasNext()){
HSSFRow r = (HSSFRow) it.next();
Iterator<Cell> it1=r.cellIterator();
while(it1.hasNext()){
HSSFCell cell = (HSSFCell)it1.next();
System.out.println("Row: "+cell.getRowIndex()+" ,Column: "+cell.getColumnIndex());
System.out.println(cell);
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}