How to write multiple data via looping to excel (Jxl) - java

In my below code, I want to write multiple data to excel but it's writing only the first value and not the remaining.
I am trying to read from webpage and write it to a excel sheet. Below is set of code works fine, but i am not able to figure out how to run this in a loop. As i have to write many value which i am reading from the table
Could anybody sort this out.
String m1 = (driver.findElement(By.xpath(".//*[#id='dhfdshjfdsfdsf']")).getText());
System.out.println(m1);
WritableWorkbook wb = Workbook.createWorkbook(new File("D:\\output_2.xls"));
writableSheet ws = wb.createSheet("customsheet",1);
{
Label label = new Label(0,0,m1);
ws.addCell(label);
}
wb.write();
wb.close();

I have edited your code to write for multiple values. Check once with below code.
WritableWorkbook wb = Workbook.createWorkbook(new File("D:\\output_2.xls"));
writableSheet ws = wb.createSheet("customsheet",1);
int rowsize = ws.getRows();
int c=0;
//if m1 contains 20 values then it upadtes till 20 rows
for(int i=rowsize; i<rowsize+20; i++) {
String m1 = (driver.findElement(By.xpath(".//*[#id='dhfdshjfdsfdsf']")).getText());
System.out.println(m1);
Label label = new Label(c,i,m1);
ws.addCell(label);
}
wb.write();
wb.close();

Related

Not able to write data in xlsx file using java?

I Have a data stored in variables and then i want to write my data to excel file(.xlsx).
(i.e) I use automation testing tools like selenium to get data from webpage and i store it in variable which i want to wrie in xlsx file
After a lot of google search I found many of users uses list or objects to write into .xlsx file.
I created a list and add my variable to that list and using looping statements (for loop) i checked whether my data is stored in list by printing it.
Then I created XSSFWorkbook and XSSFSheet and XSSFRow and XSSFCell to write data.
I write a cell by using setCellValue method to my cell.
My code successfully creates a xlsx file and sheet in it
but after execution i could not able to find any data in it.
Source code:
ArrayList<String> head = new ArrayList<String>();
head.add("Register Number");
head.add(subject1);
head.add(subject2); //subject1 and subject2 are variable i created
System.out.println(head.get(1)); //To check if my list has value
XSSFWorkbook workbook = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("/home/st.xlsx");
for (int i = 0; i < head.size(); i++)
{
XSSFRow Row = sheet1.createRow(1);
XSSFCell cell = Row.createCell(1);
cell.setCellValue(head.get(1));
sheet1.autoSizeColumn(1);
}
workbook.write(fileOut);
fileOut.close();
I expect my code add data to my file.
Main thing is During execution when i try to open my .xlsx file it has data in it.
But after the complete execution i get with the empty xlsx file.
I don't know why i'm getting this and What wrong in my code?
Thanks in advance!
ArrayList<String> head = new ArrayList<String>();
head.add("Register Number");
head.add(subject1);
head.add(subject2); // subject1 and subject2 are variable i created
System.out.println(head.get(0)); // To check if my list has value
System.out.println(head.get(1)); // To check if my list has value
System.out.println(head.get(2)); // To check if my list has value
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = wb.createSheet("Sheet1");
for (int r = 0; r < head.size(); r++)
{
XSSFRow row = sheet1.createRow(r);
XSSFCell cell = row.createCell(0);
cell.setCellValue(head.get(r));
sheet1.autoSizeColumn(0);
}
// Write this workbook to a FileOutputStream.
FileOutputStream fileOut = new FileOutputStream("/home/st.xlsx");
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
More info here:
https://gist.github.com/madan712/3912272

New Sheet is not getting created when i do Apache POI on a loop

I am facing an issue when i write huge set of data to a Excel file with multiple sheets. I am using apache POI for the excel export.
File file = new File("../path/file.xls");
FileOutputStream fout = new FileOutputStream(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int limit = 100000,offset=0,count=0,sheetIndex=0;
XSSFWorkbook workbook = new XSSFWorkbook();
do{
XSSFSheet sheet = null;
if (file.exists() && sheetIndex > 0) {
try {
workbook = (XSSFWorkbook)WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
sheet = workbook.createSheet("Sheet-"+sheetIndex);
}else{
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Sheet-"+sheetIndex);
}
Row header = sheet.createRow(0);
//...Header row creation...
List<DataType> result = query(criteria,offset,limit);
offset = offset + limit;
count = results.size();
sheetIndex++;
int rowCount = 1;
for(DataType rowData : results){
Row row = sheet.createRow(rowCount++);
//row creation....
}
try {
workbook.write(outputStream);
outputStream.writeTo(fout);
} finally {
outputStream.flush();
}
}while(count == limit);
workbook.write(outputStream);
outputStream.writeTo(fout);
outputStream.close();
fout.close();
In the loop i am fetching 100k records from DB and writing it to the excel, and each 100k i am creating a new Sheet until there are no more records from the DB.
This code have 2 issues
1. I am facing issues in opening the file, the excel file alert me that it has issues when i try to open, eventually when i say ok it loads the data.
I can see there are only 1 sheet with 100k data though my DB contains 240M records. I also can see the loop is looping for number of times.
How can i get these issues resolved? really stucked!
Thanks in advance.
The XSSFWorkbook workbook is created multiple times and it overwrites the one created on previous loop. The workbook needs to be created only once.
I suggest changing the loop entry to the following:
XSSFWorkbook workbook = new XSSFWorkbook();
do {
XSSFSheet sheet = workbook.createSheet("Sheet-"+sheetIndex);
Row header = sheet.createRow(0);
//...Header row creation...
// remaining code
I have changed WorkBook type to SXSSFWorkbook and set the flush limit to 100 and it worked.
The performance has increased 5 times better than the XSSFWorkbook.

Java write csv-String to Excel

in my program i want to write an String to *.xlsx
Example for the String:
a,b,c,d,e,,f,\na,b,c,d,e,,f,\n
I want to write an Excel file which looks like this:
How can I do this?
private void createExcel() throws Exception {
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet("Excel Sheet");
How can I create the rows and columns from my csvString?
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("FilePath.xlsx"));
workbook.write(out);
out.close();
System.out.println("*.xlsx written successfully" );
}
I'm thankful for any help
Using XSSFSheet.createRow(), you can create rows as required.
In your case, you would have to split the string by ,\n and make a XSSFSheet.createRow() call for each element of the resulting array.
Using XSSFRow.createCell(), you can create cells, for which a split by , would be required. To set the value, Cell.setCellValue() has to be invoked with each comma separated part.
Simple example here.
private void createExcel() throws Exception {
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet_1 = workbook.createSheet("Excel Sheet");
ArrayList<String> arrRows = new ArrayList<String>(Arrays.asList(Text.split("\n")));
for (int i = 0; i < arrRows.size(); i++) {
XSSFRow row = spreadsheet_1.createRow(i);
ArrayList<String> arrElement = new ArrayList<String>(Arrays.asList(arrRows.get(i).split(",")));
for(int j = 0; j < arrElement.size(); j++) {
XSSFCell cell = row.createCell(j);
cell.setCellValue(arrElement.get(j));
}
}
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("FilePath.xlsx"));
workbook.write(out);
out.close();
System.out.println("*.xlsx written successfully" );
}
Like #Naveed S said first I split my Text at every \N and create a Row for each element. Then I Split the elements at ,and create Cells
Thanks for the help and suggestion it really helped me

Read and write data to excel using POI - It deletes my original data from excel after write new data

I am first reading data from excel and then write in same excel. It works fine first time. Just after data written , It deletes my original data which was there from very beginning.
code is given below :
public static void main (String args[]) throws Exception {
//CODE TO REMOVE UNNECESSARY WARNING
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Jdk14Logger");
//CALL FIREFOX DRIVER TO OPEN IT
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.co.in/?gfe_rd=cr&ei=VQiAVOeCFavM8gf59IHACg&gws_rd=ssl#q=software+testing");
java.util.List<WebElement> links = driver.findElements(By.tagName("h3"));
int sizecount = links.size();
System.out.println(sizecount);
FileInputStream input = new FileInputStream("D:\\sel.xls");
int count=0;
HSSFWorkbook wb = new HSSFWorkbook(input);
HSSFSheet sh = wb.getSheet("sheet1");
HSSFRow row = sh.getRow(count);
String data = row.getCell(0).toString();
System.out.println(data);
FileOutputStream webdata = new FileOutputStream ("D:\\sel.xls");
int inc = 1;
for(int i=1;i<=links.size()-1;i++)
{
HSSFRow row1 = sh.createRow(count);
row1.createCell(inc).setCellValue(links.get(i).getText());
count++;
}
wb.write(webdata);
if you are updating it, you should also update the count variable with the last line of the excel
int inc = 1;
count = sh.getPhysicalNumberOfRows();
and do the rest...
you are facing the issue because the index of excel sheets are same when you are writing.
First you should check wheater the cell is empty or not then you should write.
Or you can first do getrows() or getcolumn() it will give you the size of the rows and columns.
once you have the size you can write your data after the that row size and column.

Modifying existing excel using jxl

I m not able to edit the existing excel sheet using jxl.
It always creates a new one.
Can anyone please help me out with it.
Please give a small sample code.
jxl is designed for increased read efficiency (since this is the primary use of the API). In order to improve performance, data which relates to output information (eg. all the formatting information such as fonts) is not interpreted when the spreadsheet is read, since this is superfluous when interrogating the raw data values.
However, if we need to modify this spreadsheet a handle to the various write interfaces is needed, which can be obtained using the copy method.
Workbook workbook = Workbook.getWorkbook(new File("myfile.xls"));
WritableWorkbook copy = Workbook.createWorkbook(new File("temp.xls"), workbook);
This copies the information that has already been read in as well as performing the additional processing to interpret the fields that are necessary to for writing spreadsheets. The disadvantage of this read-optimized strategy is that we have two spreadsheets held in memory rather than just one, thus doubling the memory requirements.
But after this, you can do whatever you want. Like:
WritableSheet sheet2 = copy.getSheet(1);
WritableCell cell = sheet2.getWritableCell(1, 2);
if (cell.getType() == CellType.LABEL)
{
Label l = (Label) cell;
l.setString("modified cell");
}
copy.write();
copy.close();
workbook.close();
Note: this is directly taken from Andy Khan's tutorial page.
I know that this is quite an old question, but if anyone will encounter the same problem, then to preserve the correct formatting (font type, colouring, etc. )
you should save the cell format before casting it to Label, and then force the cell to the previous formatting.
Code:
CellFormat cfm = cell.getCellFormat();
Label l = (Label) cell;
l.setString("modified cell");
cell.setCellFormat(cfm);
//there is god example of it, you can copy in ur project and check it out, to
//understand how it works
Workbook wk = Workbook.getWorkbook(new File("ex.xls"));
//
WritableWorkbook wkr = Workbook.createWorkbook(new File("modifed.xls"), wk);
/* second line makes copy of wk excel file object /creates a readable spreadsheet.
both are now similar and i can Modify exiting wkr spreadsheets */
//next 2 line retrieve sheet number 0 and cell (1,1)
WritableSheet getsht = wkr.getSheet(0);
WritableCell getcl = getsht.getWritableCell(1, 1);
//making own font
WritableFont ft = new WritableFont(WritableFont.ARIAL, 20 , WritableFont.BOLD, true , UnderlineStyle.SINGLE);
//making Format, which uses font
WritableCellFormat form = new WritableCellFormat( ft);
Number nb = ( Number ) getcl ;
nb.setCellFormat( form );
wkr.write();
wkr.close();
I personally use this code to append the xls file and create one if it doesn't exist.
Using jxl 2.6:
public class Excel {
private String fileName = "excel_file.xls";
private String sheetName = "sheet1";
private WritableWorkbook writableWorkbook;
private int rowCount;
private Workbook wb;
// assigns checks if file exists or not, both cases we assign it to a WritableWorkbook // object so that we can write to it.
private void assignWorkBook() throws IOException, BiffException {
// File f = new File(System.getProperty("user.dir") +"\\"+fileName);
File inp = new File(fileName);
try{
wb = Workbook.getWorkbook(inp);
writableWorkbook = Workbook.createWorkbook(inp, wb);
} catch (FileNotFoundException e){
writableWorkbook = Workbook.createWorkbook(inp); //Create a new one
}
}
public int getRowCount() {
return rowCount;
}
// this function writes a vector to an excel file, checks if there is already a sheet
// with that name or not, and uses it. then we have to close the Workbook object before
// we could write to the file, and then we save the file.
// That is, the file is always saved after writing to it.
public void writeRow(Vector<String> playerVector) throws WriteException, IOException, BiffException {
assignWorkBook();
WritableSheet excelSheet;
if(writableWorkbook.getNumberOfSheets() == 0) {
excelSheet = writableWorkbook.createSheet(sheetName, 0);
}
else {
excelSheet = writableWorkbook.getSheet(sheetName);
}
rowCount = excelSheet.getRows();
int colCount = 0;
for(String playerStat:playerVector) {
Label label = new Label(colCount++, rowCount, playerStat);
excelSheet.addCell(label);
}
if(wb != null) {
wb.close();
}
writableWorkbook.write();
writableWorkbook.close(); //everytime save it.
}
}

Categories