I am printing some string values in excel
In excel currently last string is printing, but I need to print them all row by row
Code
for(String a:arrOfStr)
{
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a)
}
keyword
#Keyword
public void demoKey(String name) throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
Row row = sheet.createRow(rowCount+);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("C:\\Users\\lahiruh\\Katalon Studio\\Project Decypha\\Decypha data files\\Demo1.xlsx");
workbook.write(fos);
fos.close();
Now I can get the output like(overriding each value and giving last string )
I want to see like
Try this
for(int i = 0; i < arrOfStr.size(); i++)
{
String a = arrOfStr[i];
System.out.println(a);
//CustomKeywords.'WriteExcel.demoKey'(a)
CustomKeywords.'WriteExcel.demoKey'(a,i)
}
#Keyword
public void demoKey(String name, int index) throws IOException{
FileInputStream fis = new FileInputStream("path");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.createRow(index + 1);
Cell cell = row.createCell(0);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("path");
workbook.write(fos);
fos.close();
}
}
You have to do in the following manner.
First create a set of rows
Create cell and define the cell data type.
Store the value in the cell
I provide below the structure to store the data row by row.
int rowNumber = 0; // Row number starting with 0
for (i = 0 ; i < 10 ; i++) { //This for loop can be your data set
Row row = sheet.createRow(rowNumber++);
int columnNumber = 0; //Cell or Column number starting with 0
for (j = 0 ; j < 5 ; j++) { //This for loop can be your data set
Cell cell = row.createCell(columnNumber++);
cell.setCellValue("Some string value");
}
}
Related
I am new to Selenium and I am trying to write a code to write data into excel. This code is working. However, it just write on the second row. When I change the value of "String FieldName1 to 3" it doesn't write on the next row. I change the value of header = spreadsheet.createRow(0); to (1) it did write to next row, but it is a pain to do it every time I run my test. What I need is to write the data to the next ROW everytime I run it and change the value of "String FieldName1 to 3". THANKS IN ADVANCE!
Selenium > Java > Maven
public class testBed2 {
#Test
public void writeExcel() throws IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\ExportExcel.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet( "TestData");
XSSFRow header;
header = spreadsheet.createRow(0);
header.createCell(0).setCellValue("FieldName1");
header.createCell(1).setCellValue("FieldName2");
header.createCell(2).setCellValue("FieldName3");
int rowNumber = 1;
Row row = spreadsheet.getRow(0);
//Column Count
int colCount = row.getLastCellNum();
for (int j = 0; j < colCount; j++) {
System.out.println("Col Count : " + j);
//Row Count
int rowCount = spreadsheet.getLastRowNum() + 1;
for (int i = 0; i < rowCount; i++) {
XSSFRow currentRow = spreadsheet.createRow(rowNumber);
System.out.println("Row Count : " + i);
String FieldName1 = "NAME1";
String FieldName2 = "NAME2";
String FieldName3 = "NAME3";
currentRow.createCell(0).setCellValue(FieldName1);
currentRow.createCell(1).setCellValue(FieldName2);
currentRow.createCell(2).setCellValue(FieldName3);
FileOutputStream fos = new FileOutputStream("C:\\Users\\ExportExcel.xlsx");
workbook.write(fos);
fos.close();
}
}
}
}
I think the reason why your code write just second row is, your close code is in the For loop. If you write close code at the end of {} you will get right answer. :)
I am trying to update a column in the excel sheet but only the first row is getting update. The second iteration is not working. Could anyone help me on this? Below is my code that I am trying.
String excelPath = "path";
String YES = "Updated YES";
String NO = "Updated NO";
try {
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
Cell cell = null;
FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
HSSFSheet sheet1 = workSheet.getSheetAt(0);
String data = sheet1.getRow(i+1).getCell(i).toString();
if(data.equals(TCID.get(i))){
cell = sheet1.getRow(i+1).getCell(i+2);
cell.setCellValue(YES);
workSheet.write(output_file);
}else {
cell.setCellValue(NO);
workSheet.write(output_file);
}
}
fis.close();
output_file.close();
workSheet.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My latest code is below. Now it is updating the columns but the last row is not getting updated. What am i missing.
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
HSSFSheet sheet1 = workSheet.getSheetAt(0);
//FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
}
fis.close();
//output_file.close();
//workSheet.close();
FileOutputStream output_file =new FileOutputStream(excelPath);
workSheet.write(output_file);
output_file.close();
The row and the column are both keyed off 'i', so you'll be traversing the sheet diagonally.
But certainly do the things the other people are recommending too, they are all good suggestions.
Typically when working with a two dimensional block of information, I find it useful to have one loop for rows and then nested inside that a loop for columns (or vice versa)
e.g.
for (y = startRow; y <= maxRow; y++) {
....
for (x = startCol; x <= maxCol; x++) {
.... // do something to each column in the current row
cell = sheet1.getRow(y).getCell(x);
.....
Ok, so there are a couple of things.
Declare HSSFSheet sheet1 = workSheet.getSheetAt(0); outside of your loop. You are working with the same sheet each iteration of your for loop, so this only has to be invoked once.
Your logic to get the cell data (String data = sheet1.getRow(i+1).getCell(i).toString();) will not return you the same column. On your first iteration, you'll get (R)ow 1 : (C)olumn 0. The next iteration will return R2 : C1, then R2:C2, then R3:C3, etc. Notice the pattern that you are going diagonally down the columns, not vertically.
Rows start at 0.
You only need to workSheet.write(output_file); once you have done all your processing.
If the Row does not exist you will get a NullPointerException
As you are working with a unique Cell each iteration, you just declare it in the loop (so no need for Cell cell = null; outside your loop).
Here is a an example:
try {
FileInputStream fis = new FileInputStream(excelPath);
Workbook workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i < 5; i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cell = row.getCell(0);
cell.setCellValue("Updated cell.");
}
}
FileOutputStream output_file = new FileOutputStream(excelPath);
workbook.write(output_file);
output_file.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
I think moving Cell reference inside for loop should fix it for you.
Cell cell = null;
Also you might also need to move outside if-block incase you face NullPointerException in else-block
cell = sheet1.getRow(i+1).getCell(i+2)
Something like this...
HSSFSheet sheet1 = workSheet.getSheetAt(0);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
workSheet.write(output_file)
}
i can't set the value of cell ,it works if i try this
if(1==1){
celltofill.setCellValue("test");
}
but once it enters the if condition it displays what's in syso but doesn't insert values in the cell.
any ideas about how can i solve this isssue?
here is my code:
public class testexcel {
public static void main(String[] args) throws InvalidFormatException, IOException, ParseException{
FileInputStream fis = new FileInputStream("D:\\test6.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream("D:\\edit6.xlsx");
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFSheet sheet2 = workbook.getSheetAt(1);
for(int i=1; i <= sheet.getLastRowNum(); i++) {
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell celltofill= row.createCell(5);
Cell cellres= row2.getCell(1);
if((cell.getStringCellValue()).equals(cell2.getStringCellValue())){
System.out.println((cell.getStringCellValue())+" equals "+cell2.getStringCellValue());
celltofill.setCellType(Cell.CELL_TYPE_STRING);
System.out.println("cell filled with "+cellres.getStringCellValue());
celltofill.setCellValue(cellres.getStringCellValue());
}
}
}
workbook.write(fos);
fos.close();
}
}
row.createCell(5) does exactly what it says. It creates a new empty cell every time it is called. And you are calling it for every row in sheet2 again and again although it is a cell in sheet. So even if the criterions are not fullfilled, the new empty cell is been created already in your code.
Maybe:
...
for(int i=1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
Cell celltofill= row.getCell(5);
if (celltofill == null) celltofill = row.createCell(5);
for(int i1=1;i1<sheet2.getLastRowNum();i1++){
Row row2 = sheet2.getRow(i1);
Cell cell2 = row2.getCell(0);
Cell cellres= row2.getCell(1);
...
will be more what you want?
i have an excel file with merged and formula cell which is using the VLOOKUP(B16,Data!$A$2:$C$7,3,0). In specific cell $40 is appearing as value. but when i try to read the value it is reading only 40 and skipping the $ part.
public static void main(String[] args) {
try {
String excelFilePath = "D:\\test\\1_sample1_UA Logo Order form update on 2016-12-06.xls";
InputStream input = new BufferedInputStream(new FileInputStream(
excelFilePath));
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook workbook = new HSSFWorkbook(fs);
workbook.setForceFormulaRecalculation(true);
Sheet sheet = workbook.getSheetAt(3);
Row row = sheet.getRow(15);
Cell cell = row.getCell(7);
for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
CellRangeAddress region = sheet.getMergedRegion(i); // Region of
// merged
// cells
int colIndex = region.getFirstColumn();
int rowNum = region.getFirstRow();
if (region.isInRange(15, 7)) {
CellReference cellReference = new CellReference("H15");
Row row2 = sheet.getRow(cellReference.getRow());
Cell cell2 = row2.getCell(cellReference.getCol());
// formulla evaluato
FormulaEvaluator forEvaluator = workbook
.getCreationHelper().createFormulaEvaluator();
workbook.getCreationHelper().createFormulaEvaluator()
.evaluateAll();
workbook.setForceFormulaRecalculation(true);
CellValue cellValue = forEvaluator.evaluate(cell2);
System.out.println("cell string value2 :: "
+ cellValue.formatAsString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
When I am edit a .xlsx file using Apache poi, its taking too long to save. The .xlsx file contains, formulas formatting and freeze pane. I am using the following code,
try {
FileInputStream file = new FileInputStream(new File(path));
XSSFWorkbook fWorkbook = new XSSFWorkbook(file);
XSSFSheet fSheet = fWorkbook.getSheetAt(0);
for(int i = 0; i < jTable1.getRowCount(); i++){
if(jTable1.getModel().getValueAt(i, index1).equals("1")){
XSSFCell cell = fSheet.getRow(i+1).getCell(index1);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(new Double(1));
XSSFCellStyle cs = fWorkbook.createCellStyle();
cs.setDataFormat(fWorkbook.getCreationHelper().createDataFormat().getFormat("dd/MMMM/yyyy"));
cell =fSheet.getRow(i+1).getCell(index2);
cell.setCellValue(new Date());
cell.setCellStyle(cs);
}
}
file.close();
FileOutputStream fileOutputStream = new FileOutputStream(path);
fWorkbook.write(fileOutputStream);
fileOutputStream.close();
JOptionPane.showMessageDialog(this, "Data saved successfully.");
parent.removeContent();
}catch(Exception e){
e.printStackTrace();
}
Edit 1:
The excel file: http://ge.tt/5orGWSJ2/v/0?c
Loading Data into JTable from Excel:
try {
FileInputStream file1 = new FileInputStream(new File("c:\\sample.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file1);
XSSFSheet sheet = workbook.getSheetAt(0);
int rowc=sheet.getLastRowNum()+1;
int colc=sheet.getRow(0).getLastCellNum();
Object heading[] = new Object[colc+1];
XSSFRow row1 = sheet.getRow(0);
for(int i=0, column =0; i < colc; i++){
if(i == 1){
heading[column++] = "";
}
heading[column++] = cellToString(row1.getCell(i));
}
Object [][]j=new Object[rowc-1][colc+1];
for (int i = 1; i < rowc; i++) {
row1 = sheet.getRow(i);
for (int jj = 0, column = 0; jj < colc; jj++) {
if(column == 1){
j[i-1][column++] = new Boolean(false);
j[i-1][column] = cellToString(row1.getCell(jj));
}
else{
j[i-1][column]=cellToString(row1.getCell(jj));
}
column++;
}
}
jTable1.setModel(new DefaultTableModel(j, heading){
public Class getColumnClass(int columnIndex) {
if(columnIndex == 0){
return java.lang.Integer.class;
}
else if(columnIndex == 1){
return java.lang.Boolean.class;
}
else{
return java.lang.Object.class;
}
}
});
jTable1.getColumnModel().getColumn(1).setMaxWidth(60);
jTable1.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
jTable1.getTableHeader().setReorderingAllowed(false);
} catch (IOException ex) {
JOptionPane.showMessageDialog(BarcodePrint.this, ex);
}
Writing data into excel after editing column BarcodePrint:
try {
FileInputStream file = new FileInputStream(new File("c:\\sample.xlsx"));
XSSFWorkbook fWorkbook = new XSSFWorkbook(file);
XSSFCellStyle cs = fWorkbook.createCellStyle();
cs.setDataFormat(fWorkbook.getCreationHelper().createDataFormat().getFormat("dd/MMMM/yyyy"));
Date currentdate = new Date();
XSSFSheet fsheet = fWorkbook.getSheetAt(0);
Double barcodeprintstatus = new Double(1);
int newindex = 24;
int printdate = 26;
int uniqueid = 27;
for(int i = 0; i < jTable1.getModel().getRowCount(); i++){
if(jTable1.getModel().getValueAt(i, newindex).equals("1")){
for(int k=1; k < fsheet.getPhysicalNumberOfRows(); k++){
XSSFCell cell = fsheet.getRow(k).getCell(uniqueid-1);
String uid = cell.getRawValue();
if(jTable1.getModel().getValueAt(i, uniqueid).toString().equals(uid)){
cell = (fsheet.getRow(i+1)).getCell(newindex-1);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(barcodeprintstatus);
cell = fsheet.getRow(i+1).getCell(printdate-1);
cell.setCellValue(currentdate);
cell.setCellStyle(cs);
}
}
}
}
file.close();
FileOutputStream fileOutputStream = new FileOutputStream("c:\\sample.xlsx");
fWorkbook.write(fileOutputStream); // this is taking so much of time. Approximately 1 min.
fileOutputStream.close();
}catch(Exception e){
e.printStackTrace();
}
I am unable to solve this problem. fWorkbook.write(fileOutputStream); is taking so much of time as I mentioned above. Please help. Is there any other way to save the excel file? Or can I write data partially for a single column rather than the hole workbook?
Try to improve the code.
You call fSheet.getRow(i+1) twice. Try to introduce a variable and reuse the row rather than obtain it.
cell.setCellValue(new Double(1));
Create the 1 double once before the for loop and reuse it.
XSSFCellStyle cs = fWorkbook.createCellStyle();
cs.setDataFormat(fWorkbook.getCreationHelper().createDataFormat().getFormat("dd/MMMM/yyyy"));
Move the cell style creation and initializing out of the for loop. Create it before the loop and reuse.
cell.setCellValue(new Date());
Introduce a Date variable and create the Date just once. Again before the for loop.
Add a BufferedOutputStream around the FileOutputStream.