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
Related
I am iterating through a list of data which I am sending from the runner file(FunctionVerifier.java).
When I am calling the function writeExcel() in excelHandler.java it is entering only the last data from the list that I am iterating through.
Can someone please let me know the reason and how to fix this
public void writeExcel(String sheetName, int r, int c, String data) throws IOException {
file = new FileInputStream(new File(inFilePath));
wb = new XSSFWorkbook(file);
Sheet sh;
sh = wb.getSheet(sheetName);
Row row = sh.createRow(r);
row.createCell(c).setCellValue(data);
closeExcelInstance();
FileOutputStream outputStream = new FileOutputStream(inFilePath);
wb.write(outputStream);
wb.close();
outputStream.close();
}
public void closeExcelInstance() {
try {
file.close();
} catch (Exception e) {
System.out.println(e);
}
}
FunctionVerifier.java
package Sterling.oms;
import Sterling.oms.Process.CouponValidationProcess;
import Sterling.oms.Utilities.ExcelHandler;
import java.util.ArrayList;
public class FuncVerify {
public static void main(String args[]) throws Exception {
String filePath = System.getProperty("user.dir") + "/src/test/resources/TestData/test.xlsx";
ExcelHandler excelHandler = new ExcelHandler(filePath);
excelHandler.readExcelData("Validation");
CouponValidationProcess couponValidationProcess = new CouponValidationProcess("OMS-T781");
excelHandler.createSheet();
// couponValidationProcess.enterValidationHeaderRowInExcel(filePath);
String sheet = "ValidationData";
if (excelHandler.getRowCountWhenNull(sheet) < 1) {
ArrayList<String> header = new ArrayList<>();
header.add("Test Case");
header.add("Coupon ID");
header.add("Grand Total");
header.add("Manual Grand Total");
for (int i = 0; i < header.size(); i++) {
// excelHandler = new ExcelHandler(filePath);
excelHandler.writeExcel(sheet, 0, i, header.get(i));
// excelHandler.closeExcelInstance();
}
}
}
}
The reason for only storing the last item is that Sheet.createRow as well as Row.createCell are doing exactly what their method names tell. They create a new empty row or cell each time they get called. So every times Row row = sh.createRow(r) gets called, it creates a new empty row at row index r and looses all former created cells in that row.
The correct way to use rows would be first trying to get the row from the sheet. And only if it is not present (null), then create a new row. The same is for cells in rows. First try to get them. And only if not present, then create them.
...
Sheet sh;
sh = wb.getSheet(sheetName);
Row row = sh.getRow(r); if (row == null) row = sh.createRow(r);
Cell cell = row.getCell(c); if (cell == null) cell = row.createCell(c);
cell.setCellValue(data);
...
That's the answer to your current question.
But the whole approach, to open the Excel file to create a Workbook, then set data of only one cell in and then write the whole workbook out to the file, and doing this for each cell, is very sub optimal. Instead the workbook should be opened, then all known new cell values should be set into the sheet and then the workbook should be written out.
Your approach is wrong, you open your files again for each line you want to write to Excel, then save again. You just have to create one FileInputStream and send it to your Workbook where you do all your Excel work. After you have finished writing all your lines, you can create only one FileOutputStream and export your changes in your Workbook to a file of your choice.
writeExcel()
public void writeExcel(String sheetName, int r, int c, ArrayList<String> data) throws IOException {
file = new FileInputStream(new File(inFilePath));
wb = new XSSFWorkbook(file);
Sheet sh;
sh = wb.getSheet(sheetName);
Row row = sh.createRow(r);
//Adding data column wise
for (String h : data) {
row.createCell(c++).setCellValue(h);
}
closeExcelInstance();
FileOutputStream outputStream = new FileOutputStream(inFilePath);
wb.write(outputStream);
wb.close();
outputStream.close();
}
I have to select the option one after another from dropdown say (AAA,BBB... GGG) and after selection whatever the data populate have to be written on excel. Here method clickOnPerfomanceDetails() contains the code to write it down onto Excel. My following code is writing successfully onto excel with different sheets but manually i comment other options. In all 7 times i am executing the script to get data into 7 different worksheet.
public void clickOnPerformanceDetails() throws Exception {
File file = new File("C:\\Users\\dp\\Desktop\\Performance.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
XSSFSheet sheet = wb.createSheet("AAA");
//XSSFSheet sheet = wb.createSheet("BBB");
//XSSFSheet sheet = wb.createSheet("CCC");
// XSSFSheet sheet = wb.createSheet("DDD");
//CODE
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\Performance.xlsx");
wb.write(fos);
fos.close();
}
#Test()
public void providerTest1() throws Exception {
performance_PlusTWO.hoverTest();
performance_PlusTWO.clickOnHieararchyDropDown();
performance_PlusTWO.selectOptionNais();
//AAA
performance_PlusTWO.selectAAAOption();
performancePlus_TWO.clickOnPerformanceDetails();
//BBB
//performance_PlusTWO.selectBBBOption();
//performanceP_TWO.clickOnPerformanceDetails();
//CCC
performance_PlusTWO.selectAAAOption();
performance_TWO.clickOnPerformanceDets();
}
Creating 'AAA' worksheet and running Test for performance_PlusTWO.selectAAAOption();
performancePlus_TWO.clickOnPerformanceDetails(); Then manually i comment 'AAA' option, uncomment 'BBB' option and again execute the script. How do on a single click i execute the data for all the options.
Any help will be appreciated.
Try the below approach.
public void WriteToExcelSheet(String SheetName) throws Exception {
File file = new File("C:\\Users\\dp\\Desktop\\Performance.xlsx");
XSSFWorkbook wb = (XSSFWorkbook) WorkbookFactory.create(new FileInputStream(file));
XSSFSheet sheet = wb.createSheet(SheetName);
//CODE
FileOutputStream fos = new FileOutputStream("C:\\Users\\dp\\Desktop\\Performance.xlsx");
wb.write(fos);
fos.close();
}
#Test()
public void providerTest1() throws Exception {
Select dropdown = new Select(driver.findElement(By.id("id")));
//Get all options
List<WebElement> dropdown_items = dropdown.getOptions();
//print the number of dropdown items
System.out.println(dropdown_items.size());
// Loop through all items one by one
for (int itemIndex = 0; j < dd.size(); j++) {
String option = dropdown_items.get(itemIndex).getText();
//print the sheet name
System.out.println(option);
// write the logic to select the option <=== don't forget to implement this
// logic to call function with sheet name
performance_TWO.WriteToExcelSheet(option);
}
}
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
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.
I am writing a small utility that creates a pivot table in an excel sheet using POI and I want to read the data from the pivot table back to the program which will save it as a PDF file using Itext. I am running into a problem where the program cannot read the data from the pivot table after it is created. The program only can "see" the information in the pivot table after I manually open the created file and hit the save button in excel. Does anyone know a way to read the data from the pivot table from the XSSFPivotTable object or otherwise force a way for the file to "save" so it can be accessed by the program again?
Here is a snippet of code so you can see what I'm talking about. I'm a student so any advice on best practices would be greatly appreciated as well.
public void returnPivotData() throws IOException {
FileInputStream fs = new FileInputStream(this.xlsxFile);
XSSFWorkbook book = new XSSFWorkbook(fs);
XSSFSheet dataSheet = book.getSheet("Sheet1");
AreaReference dataRef = new AreaReference("A1:E15",
SpreadsheetVersion.EXCEL2007);
XSSFPivotTable table = dataSheet.createPivotTable(dataRef,
new CellReference("A16"));
table.addRowLabel(0);
table.addColumnLabel(DataConsolidateFunction.SUM, 3);
// Save the data back to the file
FileOutputStream fsOut = new FileOutputStream(
"D:\\workspace\\test.xlsx");
book.write(fsOut);
fsOut.close();
book.close();
fs.close();
// This does not allow access
FileInputStream fsIn = new FileInputStream("D:\\workspace\\test.xlsx");
XSSFWorkbook bookNew = new XSSFWorkbook(fsIn);
XSSFSheet sheet = bookNew.getSheet("Sheet1");
for (int i = 0; i < 20; i++) {
XSSFRow rowNew = sheet.getRow(i);
XSSFCell cellNew = rowNew.getCell(0,
MissingCellPolicy.CREATE_NULL_AS_BLANK);
System.out.println(cellNew.toString());
}
fsIn.close();
bookNew.close();
}