Excel Writing results in Read-Error - java

I have some code that writes into an Excel file:
File file = new File("Path here");
File to = new File("Path here");
Workbook workbook = Workbook.getWorkbook(file);
WritableWorkbook target = Workbook.createWorkbook(to);
target.createSheet("s", 0);
Sheet source = workbook.getSheet(1);
WritableSheet targetSheet = target.getSheet(0);
copyRow(source, 1, targetSheet, 1);
workbook.close();
target.close();
Note that Path here is replaced with the actual path in the real code.
Where the copyRow() method looks like this:
private void copyRow(Sheet sourceSheet, int sourceRow, WritableSheet targetSheet, int targetRow) throws WriteException {
for(int i = 0, numOfColumn = sourceSheet.getColumns(); i < numOfColumn; i++) {
Cell source = sourceSheet.getCell(i, sourceRow);
WritableCell cell = new Label(i, targetRow, source.getContents());
targetSheet.addCell(cell);
}
}
It runs, but when I try to open the to file:
An error message, saying that the file cannot be opened, shows when I use my Windows computer to open the same file.
Why does that happen? How do I fix it?

Related

Excel file gets corrupted when i change the value of any cell in the header (Columns Title)

I'm trying to read and Xslx file using JAVA POI, edit it and save it. But when i change any cell value on row#0 (Header) the output file gets corrupted.
Excel can recover the file by repairing, Table from /xl/tables/table.xm .
FileInputStream file = new FileInputStream("inventorywithbin431.xlsx");
XSSFWorkbook workbook = (XSSFWorkbook) WorkbookFactory.create(file);
XSSFSheet rawdata = workbook.getSheetAt(0);
String[] headers = new String[] { "ItemCodeNoFRU","Company","ItemCode","ItemName","ItemGroup","PartNumber","Warehouse","Segment","Bin","WareHouseQty","OnOrder","IsCommited","BinQty","Cost","BinExtCost"};
//Set Header
for(int i=0;i<14;i++)
rawdata.getRow(0).getCell(i).setCellValue(headers[i]);
file.close();
//write changes
try (
FileOutputStream output_file = new FileOutputStream("inventorywithbin431.xlsx")) {
workbook.write(output_file);
output_file.flush();
output_file.close();
}

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

why I cannot open the excel file which create by fastExcel

as the title said;
I create a .xls file by the lib called fastExcel successfully,but I cannot open it on my win7 systems normally.
this is my code for create the .xls file:
private static List<String[]> readLocationInfos(String path, String type) throws Exception {
Workbook workBook = FastExcel.createReadableWorkbook(new File(path));
workBook.open();
Sheet s = workBook.getSheet(0);
List<String[]> result = new ArrayList<String[]>();
for (int i = s.getFirstRow(); i < s.getLastRow(); i++) {
String[] row = s.getRow(i);
result.add(row);
}
// if(i!=0)
// converte(row, type);
workBook.close();
return result;
}
private static void output(List<String[]> list, String outputPath) throws ExcelException, IOException {
File outputFile = new File(outputPath);
Workbook workBook = FastExcel.createWriteableWorkbook(outputFile);
workBook.open();
Sheet sheet = workBook.addStreamSheet("sheet1");
for(String[] row : list)
sheet.addRow(row);
workBook.close();
}
I read the datas from another .xls file,and i want to do some converte to generate a new .xls file;
At last,I can read the new .xls file by the readLocationInfos method,but only can't open on my win7 system?
Will it was cause by a license problem?
Can anyone help me? thanks a lot..

How can I write Test Result (Pass/Fail) in Excel file using TestNG Framework with Selenium WebDriver?

How can I write result in Excel using Selenium WebDriver?
public static void writeData(String pathOfFile, String sheetName, int rowNum, int cellNum, String value) throws InvalidFormatException, IOException{
FileInputStream fis = new FileInputStream("C:\\Users\\harini.b\\Desktop\\Copy of Login.xls");
Workbook wb = WorkbookFactory.create(fis);
wb.getSheet(sheetName).getRow(rowNum).createCell(cellNum).setCellValue(value);
//wb.getSheet(sheetName).createRow(rowNum).createCell(cellNum).setCellValue(value); //use this if you are writing in new row.
FileOutputStream fos = new FileOutputStream(pathOfFile);
wb.write(fos);
}
Use Apache POI to write your results to an excel file.
Download Apache POI jar files
Add all jar files to the classpath
Imports:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
Code:
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sample.xlsx");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Blahblah");
//finally write data to excel file
FileOutputStream out = new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
See more examples at this link
Hi You can use JXL jar and some useful classes in that to read and write into excel file using testng framework.
You can read from HERE
Otherwise read with examples Write Test Case PASS/FAIL using selenium
Example:
public class Excelutility {
public String Testcase;
public WritableSheet writablesh;
public WritableWorkbook workbookcopy;
#BeforeTest
public void queryParameterization() throws BiffException,IOException,RowsExceededException,WriteException, InterruptedException{
FileInputStream testfile = new FileInputStream("E:\\AppiumTutorials\\Selenium_Practice\\SeleniumYoutube\\Testdata\\TestData.xls");
//Now get Workbook
Workbook wbook = Workbook.getWorkbook(testfile);
//Now get Workbook Sheet
Sheet sheets = wbook.getSheet("Query_data");
int Norows = sheets.getRows();
//Read rows and columns and save it in String Two dimensional array
String inputdata[][] = new String[sheets.getRows()][sheets.getColumns()];
System.out.println("Number of rows present in TestData xls file is -"+Norows);
//For writing the data into excel we will use FileoutputStream class
FileOutputStream testoutput = new FileOutputStream("E:\\AppiumTutorials\\Selenium_Practice\\SeleniumYoutube\\Testdata\\TestData_results.xls");
System.out.println("creating file one");
//To Create writable workbook
workbookcopy = Workbook.createWorkbook(testoutput);
System.out.println("creating file 2");
//To Create Writable sheet in Writable workbook
writablesh = workbookcopy.createSheet("Query_data",0);
System.out.println("creating file 3");
//Using for loop to write all the data to new sheet
for(int i=0;i<sheets.getRows();i++)
{
for(int k=0;k<sheets.getColumns();k++)
{
inputdata[i][k] = sheets.getCell(k, i).getContents();
Label l = new Label(k, i, inputdata[i][k]);
Label l2 = new Label(4,0,"Results");
writablesh.addCell(l);
writablesh.addCell(l2);
}
}
}
#AfterTest
public void writeexcels(){
try {
workbookcopy.write();
} catch (IOException e) {
e.printStackTrace();
}
try {
workbookcopy.close();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

editing an excel sheet using Apache poi

i am trying to edit an excel sheet using apache poi,
I have a worksheet having 2 rows and 5 columns
if second cell of row 2 is null then it should add a 3rd row ,
but i am getting a class not found exception, although the UpdateXLS is present in my D drive.
Here is the code:
public class New {
public static void main(String[] args){
try{
InputStream inp = new FileInputStream("D:\\UpdateXLS.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(2);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
wb.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
}
}
What should i do ?
From the comment , I can suggest you that check file exits on the path specified.
Use File
File f = new File("D:\\UpdateXLS.xls");
//check whether file exists or not to avoid any further exceptions
if(f.exists()){
Workbook wb = WorkbookFactory.create(f);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
......
.......
........
}
FileNotFoundException
Signals that an attempt to open the file denoted by a specified pathname has failed.
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist.
It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
When you are writing a file check your path
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
Change to
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");
The problem seems to be at
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
try to replace the line with:
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");

Categories

Resources