Java change cell content instead of creating new cells - java

I have a list of variables in an excel file which I use as input for an online app and generate a result. That occurs successfully however when I try to save the output in that same file by adding a new column and cells, the original content of the file would be deleted. I only want to add the info to the same document but the only option I found by googling is to create another file.
just to clarify:Variables for input
and instead of just adding the info this happens Changed document.
How can I fix it without adding more parameter and re-adding the info?
#Keyword
public void demoKey(String name) throws IOException{
FileInputStream fis = new FileInputStream("C://Users/i2srsm/Desktop/New Microsoft Excel Worksheet.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("Data for full set");
int columnNumber = sheet.getRow(0).getLastCellNum();
int firstRow = sheet.getFirstRowNum();
int lastRow = sheet.getLastRowNum();
sheet.createRow(firstRow).createCell(columnNumber).setCellValue('Proposta');
for (int rn=(firstRow); rn<=lastRow; rn++){
Cell cell = sheet.createRow(rn).createCell(columnNumber+1)
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
FileOutputStream fos = new FileOutputStream("C://Users/i2srsm/Desktop/New Microsoft Excel Worksheet.xlsx");
workbook.write(fos);
fos.close();
}
}
}

don't use a sheet.createRow(row index) for update the existing excel file. this one create a new row. if you want to update the existing row in a sheet, firstly get related existing row and then create a new cell.
for get existing row
Row row = sheet.getRow(row index);
for create a new cell in above existing row
Cell cell = row.createCell(cell index);
try with this
sheet.getRow(firstRow).createCell(columnNumber).setCellValue("Proposta");
for (int i=(firstRow+1); i<=lastRow; i++){
Row row = sheet.getRow(i);
Cell cell = row.createCell(columnNumber);
cell.setCellType(cell.CELL_TYPE_STRING);
cell.setCellValue(name);
}
FileOutputStream fos = new FileOutputStream("C:/Users/LifeStyle/Documents/output.xlsx");
workbook.write(fos);
fos.close();

Related

How to add columns to an existing large excel file using SXSSF Apache POI?

I am working with a large excel file ( larger than 40 Mb , more than 100k rows and 50 columns ). I am successfully reading it using POI ( 3.10.1 version ) event stream and then doing some calculation and storing result into a List.
Now I have to append this List as a column in the same file. In this part I am facing issue.
I have tried to achieve this by using the below code
FileInputStream excelFile = new FileInputStream(new File(pathToFile));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0); // Get first sheet
Iterator<Row> iterator = datatypeSheet.iterator();
int i=0;
while (iterator.hasNext()) { // Loop over each row
Row currentRow = iterator.next();
Cell cell = currentRow.createCell(currentRow.getLastCellNum());
cell.setCellType(Cell.CELL_TYPE_STRING);
if(currentRow.getRowNum() == 0)
cell.setCellValue("OUTPUT-COLUMN"); // set column header for the new column
else {
cell.setCellValue(list.get(i)); // list contains the output to populate in new column
i++;
}
}
FileOutputStream fos = new FileOutputStream(new File(pathToOutput));
workbook.write(fos);
fos.close();
It is working fine with smaller files But the issue is that I am getting Out of memory for the larger files. Now I tried to modify this and use SXSSF in place of XSFF to get over the memory issue (See below code). But while testing even for smaller files I am getting output file same as the input file.
FileInputStream excelFile = new FileInputStream(new File(pathToFile));
XSSFWorkbook xwb = new XSSFWorkbook(inputStream);
inputStream.close();
SXSSFWorkbook wb = new SXSSFWorkbook(xwb,100);
wb.setCompressTempFiles(true);
SXSSFSheet sh = (SXSSFSheet) wb.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
int i=0;
while (iterator.hasNext()) { // Loop over each row
Row currentRow = iterator.next();
Cell cell = currentRow.createCell(currentRow.getLastCellNum());
cell.setCellType(Cell.CELL_TYPE_STRING);
if(currentRow.getRowNum() == 0)
cell.setCellValue("OUTPUT-COLUMN"); // set column header for the new column
else {
cell.setCellValue(list.get(i)); // list contains the output to populate in new column
i++;
}
}
FileOutputStream fos = new FileOutputStream(new File(pathToOutput));
wb.write(fos);
fos.close();
Using a db is not suitable in my use case and i want to avoid using a temporary data structure to hold data for writing due to memory constraint.
Is there a way to write in output workbook while streaming ? Here is the code that I am using to read using POI Streaming API
private class ExcelData implements SheetContentsHandler {
LinkedHashMap<Strin, String> rowMap;
public void startRow(int rowNum) {
}
public void endRow(int rowNum) {
// Process the row
// Handle write to output workbook ??
}
public void cell(String cellReference, String formattedValue,
XSSFComment comment) {
// Save current row in rowMap ( column name => cell value )
}
public void headerFooter(String text, boolean isHeader, String tagName)
{
}
}
It is not possible to add column to existing workbook using POI SXSSF. It only allows addition of new rows.
The only solution is to read the existing workbook and write to a new workbook with the added column.
To achieve this we can store the rows in a data structure or database in the endrow() method and then use the persisted data to write a new workbook.

To write the value fetched from the textbox into the column of Excel through POI using Selenium

I have fetched the value from the textbox and stored in a string. Now i want to write this value stored in string into the column named as 'Username' in the excel file.
E.G: Fetched the Username from the textbox as 'Test1' and want to write this in the column 'Username' of the Excel. I am using POI to write excel file using Selenium.
hi please implement the logic like below
public static void writeExcel(String filePath,String fileName,String sheetName,String[] dataToWrite) throws IOException{
//Create a object of File class to open xlsx file
File file = new File(filePath+"\\"+fileName);
//Create an object of FileInputStream class to read excel file
FileInputStream inputStream = new FileInputStream(file);
Workbook Workbook = null;
//Find the file extension by spliting file name in substing and getting only extension name
String fileExtensionName = fileName.substring(fileName.indexOf("."));
//Check condition if the file is xlsx file
if(fileExtensionName.equals(".xlsx")){
//If it is xlsx file then create object of XSSFWorkbook class
Workbook = new XSSFWorkbook(inputStream);
}
//Check condition if the file is xls file
else if(fileExtensionName.equals(".xls")){
//If it is xls file then create object of XSSFWorkbook class
Workbook = new HSSFWorkbook(inputStream);
}
//Read excel sheet by sheet name
Sheet sheet = Workbook.getSheet(sheetName);
//Get the current count of rows in excel file
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
//Get the first row from the sheet
Row row = sheet.getRow(0);
//Create a new row and append it at last of sheet
Row newRow = sheet.createRow(rowCount+1);
//Create a loop over the cell of newly created Row
for(int j = 0; j < row.getLastCellNum(); j++){
//Fill data in row
Cell cell = newRow.createCell(j);
cell.setCellValue(dataToWrite[j]);
}
//Close input stream
inputStream.close();
//Create an object of FileOutputStream class to create write data in excel file
FileOutputStream outputStream = new FileOutputStream(file);
//write data in the excel file
Workbook.write(outputStream);
//close output stream
outputStream.close();
}
Now call the above in main method like below
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
String valueToWrite = "test 1";
//Create an object of current class
WriteExcelFile objExcelFile = new WriteExcelFile();
//Write the file using file name , sheet name and the data to be filled
objExcelFile.writeExcel(System.getProperty("user.dir")+"\\src\\excelExportAndFileIO","ExportExcel.xlsx","ExcelDemo",valueToWrite);
}
You need to know column number of "Username" column in the excel sheet. Once you know that then it will be easy to write value of String that you captured from webpage. You can take below approach -
File excelFile = new File("C:\\path\\of\\excel\\file\\excel.xlsx");
String cellNo = 3; //column number of "UserName" column
String rowNo = 1; // row number
String userName = "Test1"; // username fetched from textbox
FileInputStream fis = new FileInputStream(excelFile);
XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(rowNo);
row.createCell(cellNo).setCellValue(userName);
fis.close();
FileOutputStream fos = new FileOutputStream(excelFile);
workbook.write(fos);
fos.close();
This is very simple approach just for this purpose and is not generalized one for any other task.
You can take a look at simple script that reads from a excel sheet and writes back to same excel sheet using Apache POI, here.
Regards,
Punkaaj

Cant write more than one row in excell sheet using POI

I'm developing an app in java using POI, which writes data into excell sheet.
I want to write a new row when I have a new data (in order to assist the user to follow the data).
I dont want to close and reopen the excell file each time I have a new data to write.
The initilize code is:
FileOutputStream fileOut = new FileOutputStream(new File (excellFileName));
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
rowNum = 0;
HSSFRow rowhead = sheet.createRow((short)rowNum);
createRowColumns(rowhead, rowNum);
workbook.write(fileOut);
rowNum++;
Each time I have a new data, I'm using this code:
HSSFRow rowMsg = sheet.createRow((short)rowNum);
createRowColumns(rowMsg, rowNum);
workbook.write(fileOut);
rowNum++;
(createRowColumns mehtod sets the data (in seperate cells in a new: rowMsg)
The problem is that I cant see any rows in the excell file, except the first row (rowhead , row #0).
What Am I missing ?
(Pay attention that I dont want to close and reopen the file each time I have data to write)
Thanks
To write all rows you have to write to worksheet only once. So, you need to update your code as follows.
for(int index = 0; index < rowNum; rowNum++) {
HSSFRow rowMsg = sheet.createRow((short)rowNum);
createRowColumns(rowMsg, rowNum);
}
workbook.write(fileOut);

adding cells in excel with java apache

I am reading an already existing excel file and trying to add certain cells for example(C4-C15). I am having difficult manipulating the files through java. I am using apache poi, and would appreciate any help or direction.
In order to access a cell in Apache POI, you have to get a row first, and then get cell within chosen row. Below is example:
//Input file
InputStream inp = new FileInputStream("workbook.xls");
//Create workbook instance
Workbook wb = WorkbookFactory.create(inp);
//Create sheet instance
Sheet sheet = wb.getSheetAt(0);
for(int i = 3; i <= 16; ++i){ //Rows from 4 to 15 (Apache POI is zero based)
Row row = sheet.getRow(i);
Cell cell = row.getCell(2); //Column "C"
//Do something with cell
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
Source (more examples here)

How to write on a null cell using java?

I am currently doing a program in Java that will run several tests and generate a report right after in excel. I was able to read and write through excel and the results of Passed or Failed are displayed in Results column. I was able to write these in excel but by supplying a default value on the cell (e.g. default) so the code will just overwrite it. I would like to write a comment on the Comment column, but I do not know how to write in a null cell. Here is a screenshot of the report I am generating (the link of the image available) and the code for reading and writing in excel as well.
FileInputStream fileInputStream = new FileInputStream("ReportExcel.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheetAt(0);
fileInput csvInputFile = new fileInput();
String[] sReturnValue = csvInputFile.arrayReturnSingleValue("fileInput.csv");
if (prodnameresult.equals(prodname) ){
Pass++;
totalResult++;
System.out.println ("Testcase1: Branding-Customised Product Name is PASSED");
//Harold's Input
HSSFRow row = worksheet.getRow(1);
HSSFCell cell = row.getCell((short) 4);
cell.setCellValue("Passed");
}
else{
Fail++;
totalResult++;
System.out.println("Testcase1: Branding-Customised Product Name is FAILED");
//assertEquals(prodnameresult.equals(prodname), true);
//Harold's Input
HSSFRow row = worksheet.getRow(1);
HSSFCell cell = row.getCell((short) 4);
cell.setCellValue("Failed");
}
//Harold's Input
FileOutputStream os = new FileOutputStream("ReportExcel.xls");
workbook.write(os);
os.close();
}
Report:
http://i47.tinypic.com/2s1lsfc.png
I don't have access to the report, but to answer to your question, if your cell is null you should create it and not get it as following:
HSSFCell cell = row.getCell((short) 4);
if(cell == null)
cell = row.createCell((short) 4);
cell.setCellValue("Passed");
You should maybe re-apply the Style to the Cell if it had a different one from the row.

Categories

Resources