In my previous blog post , I have mentioned how to read from an excel file using jxl jar files in Java. It can be found here
In this post, I will explain how to write into an excel using same library. Below example will update the excel cell content with the value passed and also update its formatting . The color of the cell will change depending on value we pass. We can use similar functions for updating any other cell format.
publicvoidWriteDataIntoExcelCell(Stringsheet,Stringfield_name,intRow,Stringinput){try{Workbookwrk1=Workbook.getWorkbook(newFile(dataPath));//Obtain the reference to the first sheet in the workbookSheetsheet1=wrk1.getSheet(sheet);intx=0;inty=0;intCol=0;// Find Column number from excel by iteration first row and comparing the namesCellcolArow1=sheet1.getCell(x,y);do{colArow1=sheet1.getCell(x,y);if(colArow1.getContents().equalsIgnoreCase(field_name)){Col=colArow1.getColumn();break;}x=x+1;}while(colArow1.getContents()!="");// write to fileFileexlFile=newFile(dataPath);WritableWorkbookwritableWorkbook=Workbook.createWorkbook(exlFile,wrk1);WritableSheetwritableSheet=writableWorkbook.getSheet(sheet);//WritableCellFormat writableCell = writableWorkbook.getSheet(sheet).// Update cell content and formatStringVarcolour;Labellabel;if(input.equalsIgnoreCase("PASS")){label=newLabel(Col,Row,input,getCellFormat(Colour.GREEN));}elseif(input.equalsIgnoreCase("FAIL")){label=newLabel(Col,Row,input,getCellFormat(Colour.RED));}else{label=newLabel(Col,Row,input);}//Label label = new Label(Col,Row,input);writableSheet.addCell(label);writableWorkbook.write();writableWorkbook.close();}catch(BiffExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}catch(WriteExceptione){e.printStackTrace();}}privatestaticWritableCellFormatgetCellFormat(Colourcolour)throwsWriteException{WritableFontcellFont=newWritableFont(WritableFont.TAHOMA,10);WritableCellFormatcellFormat=newWritableCellFormat(cellFont);cellFormat.setBackground(colour);returncellFormat;}