why I cannot open the excel file which create by fastExcel - java

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..

Related

zip file instead of an excel file when using XSSFWorkbook in java how do I open this

I am trying to write an excel file using java. I'm looking for just simply a column with one username per row right now, and then will build upon this later once I understand what is going a bit better. I get a zip file instead of the expected excel file, and it contains docProps, _rels, xl, and [Content_Types].xml. I don't understand how to open this zip file as though it is an excel file. I have not had luck finding the answer as all the tutorials I see show it to be a straight forward excel file, not a zip file. Is it a configuration I'm missing or is it to do with linux?
Here's my code, and what I end up with:
private void createExcelSheet(Assignment assignment) throws FileNotFoundException {
String excelFilePath = Configuration.DIRECTORY_ROOT+"/tests/"+assignment.getAssn_number()+"/gradebook-"+assignment.getAssn_number();
int rowNum = 0;
int col = 0;
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(assignment.getAssn_number()+" Grades ");
XSSFRow row = spreadsheet.createRow(rowNum);
Cell cell;
for (User user : userService.getUsers() ) {
row = spreadsheet.createRow(rowNum);
cell = row.createCell(rowNum);
cell.setCellValue(user.getStudent_id());
rowNum++;
}
try (FileOutputStream fos = new FileOutputStream(excelFilePath)) {
workbook.write(fos);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

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

how to upload single excel doc with multiple sheets to a multiple table using java

i am trying to upload a excel document with multiple sheets
e.g file name: payroll that contains
sheet 0
sheet 1 and etc....
and i have a multiple database table like table 1, table 2 and etc.....
Now i am trying for map sheet 0 to table 1
sheet 1 for table 2 and etc using java
i am already using single sheet to one table
e.g code:
/**
*
*/
private static final long serialVersionUID = 1L;
public File file;
private int totalRecords=0;
private int successRecords=0;
private int failureRecords=0;
private String totalMsg="Total No. of records processed :";
private String successMsg="No. of records succeeded :";
private String failureMsg="No. of records failed:";
#SuppressWarnings("deprecation")
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Output stream to write to
try {
// Open the file for writing.
file = new File("" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
UI.getCurrent().showNotification(
"Could not open file<br/>", e.getMessage(),
Notification.TYPE_ERROR_MESSAGE);
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
try{
Session session = com.systems.payrolladmin.PayrolladminMainUI.sf.openSession();
session.beginTransaction();
//File excel = new File(FILE_PATH);
FileInputStream fis = new FileInputStream(file);
#SuppressWarnings("resource")
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);
Row row;
ArrayList<Resignee> ErrorDataList2 = new ArrayList<Resignee>();
int LastRowNum=sheet.getLastRowNum();
for(int i=1; i<=LastRowNum; i++){
row = sheet.getRow(i);
String vempId1 = row.getCell(1).getStringCellValue();
Date vdor1=row.getCell(3).getDateCellValue();
Date vdorr=row.getCell(4).getDateCellValue();
String vRemark = row.getCell(5).getStringCellValue();
int a=5;
int b=5;
if(a==b)
{
Resignee resobj = new Resignee();
resobj.setEmpId(vempId1);
resobj.setDOR(vdor1);
resobj.setDOReliv(vdorr);
resobj.setRemarks(vRemark);
session.save(resobj);
resobj=null;
successRecords++;
}else{
Resignee error = new Resignee();
error.setEmpId(vempId1);
error.setDOR(vdor1);
error.setDOReliv(vdorr);
error.setRemarks(vRemark);
error.setRemarks(vRemark);
ErrorDataList2.add(error);
error=null;
failureRecords++;
}
totalRecords++;
}
session.getTransaction().commit();
session.close();
fis.close();
//write to excel
#SuppressWarnings("resource")
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("employe db");
XSSFRow xrow=spreadsheet.createRow(0);
XSSFCell cell;
cell=xrow.createCell(0);
cell.setCellValue("EMPLOYEE ID");
cell=xrow.createCell(1);
cell.setCellValue("DOR");
cell=xrow.createCell(2);
cell.setCellValue("DORELIEVE");
cell=xrow.createCell(3);
cell.setCellValue("REMARKS");
int i=1;
for (Resignee nobj : ErrorDataList2) {
xrow=spreadsheet.createRow(i);
cell=xrow.createCell(0);
cell.setCellValue(nobj.getEmpId());
cell=xrow.createCell(1);
cell.setCellValue(nobj.getDOR());
cell=xrow.createCell(2);
cell.setCellValue(nobj.getDOReliv());
cell=xrow.createCell(3);
cell.setCellValue(nobj.getRemarks());
i++;
}
FileOutputStream out = new FileOutputStream(
new File("F:\\Error Excel\\ResingeeError.xlsx"));
workbook.write(out);
out.close();
Your question makes it sound like your code is working for a single sheet. If that is true, then the line that gets the first sheet,
XSSFSheet sheet = book.getSheetAt(0);
can be updated to look at multiple sheets as shown in this question Use
book.getNumberOfSheets();
to get the number of sheets in the workbook and then process each separately was you are already doing with sheet 0

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();
}
}

Categories

Resources