Unable to open hyperlinked file Apache POI - java

My hyperlinked files reside in Whois dir and both dir and the Excel file are in the same parent directory. I am unable to access my files through Hyperlinks because of relative paths. I need to send this Excel file to several recipients without any change to their options. I have tried getPath(), getCanonicalPath() and getAbsolutePath() to no avail. Here is my code:
public void writeTheFile() throws Exception {
int rowNum=-1;
String line = "";
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("Contact & Whois");
XSSFCreationHelper helper = workBook.getCreationHelper();
BufferedReader br = new BufferedReader(new FileReader(INPUT_FILE));
while((line = br.readLine()) != null) {
rowNum++;
XSSFRow currentRow=sheet.createRow(rowNum);
currentRow.createCell(0).setCellValue(line.trim());
currentRow.createCell(1);
XSSFHyperlink file_link_downloads = helper.createHyperlink(Hyperlink.LINK_FILE);
Cell cell = sheet.getRow(rowNum).getCell(1);
try {
File f = new File("Whois/" + line + ".whois.txt");
if(f.exists()) {
cell.setCellValue("[Whois]");
String path = f.getPath();
file_link_downloads.setAddress(path);
cell.setHyperlink((org.apache.poi.ss.usermodel.Hyperlink) file_link_downloads);
} else {
cell.setCellValue("-NA-");
}
} catch (Exception e) {
System.out.println("Error in setting up download link");
e.printStackTrace();
}
}
On windows path is being persisted on another computer verbatim.

Excel sets relative link from current file location. So, you have to check file existence and then set relative path.
Example:
Hyperlink hyperlink = creationHelper.createHyperlink(Hyperlink.LINK_FILE);
String relativePath = "../parentdir/fileToLink.txt";
hyperlink.setAddress(relativePath);
hyperlink.setLabel("Link to file");
cell.setHyperlink(hyperlink);
cell.setCellValue("Link to file");
cell.setCellType(Cell.CELL_TYPE_STRING);
If excel file in the same directory with linked files, just specify link as hyperlink.setAddress("fileToLink.txt").

Related

how to solve - Getting OLE2 exception while opening .xls excel file using selenium+java

Hello All
Hey,it's omkaar as a software tester(Automation Selenium+Java).
There is a scinario of reading excel file using Automation (selenium+java)which having .xls (Microsoft Excel 97-2003 Worksheet) file extension.
Now i am not able to read excel file due to the error/popup massege(Please have look attched screenshot) which is obsereved while opening that file manually.
Steps which i have followed to read excel file.
Created object of file class and give the refference of that perticular file.
Created workbook instance.
Created sheet, row and cell instance.
Used "for each loop" to iterate through each cell to get the data.
(You can also go through attached code.)
here is my code.
public class WorkWithXLSFile extends BaseTest {
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\Omkar Shrotri\\Downloads\\Ticketdetails.xls");
if (file.exists()) {
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet1 = wb.getSheetAt(0);
DataFormatter formatter11 = new DataFormatter();
for (int i = 0; i <= 7; i++) {
String excel_data = formatter11.formatCellValue(sheet1.getRow(2).getCell(i));
// int s = i+1;
String web_data = driver.findElement(By.xpath("//table/tbody/tr[1]/td['" + i + "']")).getText();
if (excel_data.equals(web_data)) {
System.out.println("Passed");
}
}
}
} catch (Exception NotOLE2FileException) {
System.out.print(NotOLE2FileException);
// handle popup
// try code
}
}
}

Force close an excel file before writing to it

I am writing to an existing excel file using Java, say this is fileA. (I'm using APACHE POI for this.)
It is possible that the excel fileA is opened by someone. It is saved in a shared folder accessed by a lot of people.
I want to avoid encountering
java.io.FileNotFoundException: (The process cannot access the file
because it is being used by another process)
Because no matter if the existing excel file is opened or not, I need to save the output of my Java app.
Upon researching, I think it is impossible to close fileA (opened by some other process/user, not by my Java App) within my Java code.
What I'm doing now is to create a new excel file, say fileB if fileA is currently opened. I'm using the code below.
File file = null;
FileOutputStream out = null;
int workbookNo = 0;
do{
String append = "";
if(workbookNo != 0){
append = "_Copy" + Integer.toString(workbookNo);
}
file = new File(filePath + "ValidateLock_" + dataDate + append + ".xlsx");
try{
out = new FileOutputStream(file);
workbookNo = 0;
}catch(FileNotFoundException e){
//e.printStackTrace();
workbookNo++;
}
}while(workbookNo != 0);
However, I'm getting the error below.
org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException: No
valid entries or contents found, this is not a valid OOXML (Office
Open XML) file
try like this :
try {
FileInputStream file = new FileInputStream(new File("C:\\update.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(1).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(2).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(3).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
//Close the excel input file (inputstream)
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
//Close output excel file
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Is it possible to write an Excel file using usermodel and read the same file again using eventmodel in apache poi

I tried writing to a new Excel file using the following code (uses usermodel)
private static void writeToExecelFileUsingUserModel() throws InvalidFormatException, IOException {
String[] header = {"","A","B","C", "D","E","F","G","I","J"};
String[] dataSet = {"1","2","3","4","5","6","7","8","9","10"};
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = (HSSFSheet) workbook.createSheet("testSheet");
HSSFRow row = sheet.createRow(0);
for(int i= 0; i <header.length; i++ ){
HSSFCell cell = row.createCell(i);
cell.setCellValue(header[i]);
}
HSSFRow row2 = sheet.createRow(1);
for(int i= 0; i <dataSet.length; i++ ){
HSSFCell cell = row2.createCell(i);
cell.setCellValue(dataSet[i]);
}
try {
FileOutputStream fos = new FileOutputStream("C:\\Test.xls");
workbook.write(fos);
System.out.println("write complete");
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Then, I used the same file and tried reading using eventmodel using the code below. It gave the error:
Exception in thread "main"
org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package
should contain a content type part [M1.13] at
org.apache.poi.openxml4j.opc.ZipPackage.getPartsImpl(ZipPackage.java:199)
at
org.apache.poi.openxml4j.opc.OPCPackage.getParts(OPCPackage.java:665)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:274)
at
com.benz.test.ReadFromExcel.readUsingEventModel(ReadFromExcel.java:34)
at com.benz.test.ReadFromExcel.main(ReadFromExcel.java:24)
//code for reading from previously generated xls file using eventmodel
private static void readUsingEventModel() throws IOException, OpenXML4JException {
InputStream excelStream = null;
OPCPackage pkg = null;
System.out.println("reading using event model");
try {
FileInputStream myxls = new FileInputStream("C:\\Test.xls");
pkg = OPCPackage.open(myxls);
XSSFReader xssfReader = new XSSFReader(pkg);
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
String sheetName = iter.getSheetName();
System.out.println("sheet name is"+sheetName);
} finally {
if (excelStream != null) {
excelStream.close();
}
if (pkg != null) {
pkg.close();
}
}
}
Also the same scenario (ie writing using usermodel and reading using event model) works fine for xlsx file but does not work for xls files.
Also I cannot use usermodel for reading as it is giving performance issues
Any help would be greatly appreciated.Thanks
Your first set of code is all HSSF, which only works for .xls files:
HSSFWorkbook workbook = new HSSFWorkbook();
Then, a little later, you're suddenly trying to use the XSSF code which only works for .xlsx files:
OPCPackage pkg = null;
XSSFReader xssfReader = new XSSFReader(pkg);
You have two choices. Firstly, you can change your initial code to be XSSF, using XSSFWorkbook and friends. If you generate your Excel file with XSSF as a .xlsx, then you can read it with XSSF code. Alternately, if you really want to be using HSSF / .xls for generation, and you want to use low-memory reading, then you need to use the HSSF Event API to do your read

Getting error "Your InputStream was neither an OLE2 stream, nor an OOXML stream" when created file through apache POI

I am trying to check if my excel file already exists. If it doesn't exists, I want to create a new one and if it exists I will delete it and create a new one. I wrote following program but I am getting error at line - workbook= WorkbookFactory.create(instream);
The error is->
java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXML stream
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:89)
at tryIng.main(tryIng.java:84)
Here is a program ->
try {
String filePath= "C:/Users/pritik/Desktop/t1.xlsx";
File file = new File(filePath);
filePath= file.getAbsolutePath();
xlFile = new File(filePath);
if(xlFile.exists() && !xlFile.isDirectory())
xlFile.delete(); //delete if file already exists.
xlFile.createNewFile();
inStream = new FileInputStream(xlFile);
workbook = WorkbookFactory.create(inStream); // I get error at this line
String sheetName="NewSheet";
Sheet sheet = workbook.createSheet(sheetName);
FileOutputStream fOut = new FileOutputStream(xlFile);
int i,j;
xRows = xTS.length;
xCols = xTS[0].length;
for(i =0;i<xRows;i++)
{
row = sheet.createRow(i);
for(j=0;j<xCols;j++)
{
cell = row.createCell(j);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(xTS[i][j]);
}
}
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't create an empty file and try to read it, that won't work. An empty zero byte file is not valid, and can't be loaded Instead, have POI create an new file for you, which you will write later.
Change the code:
if(xlFile.exists() && !xlFile.isDirectory())
xlFile.delete(); //delete if file already exists.
xlFile.createNewFile();
inStream = new FileInputStream(xlFile);
workbook = WorkbookFactory.create(inStream);
To instead be:
if(xlFile.exists() && !xlFile.isDirectory())
xlFile.delete(); //delete if file already exists.
if (xlFile.toString().endsWith(".xls") {
workbook = new HSSFWorkbook();
} else {
workbook = new XSSFWorkbook();
}
Also, if you do want to read an existing file, don't use a stream if you have a file! See this bit of the POI docs for why not.

make specific path on Excel POI

I want to make a path that saved in database.
here's my code.
#RequestMapping("import_excel")
#ResponseBody
public Map<String, ? extends Object> import_excel() {
modelMap.clear();
try {
HttpSession session = req.getSession();
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("Export");
Row row1 = sheet.createRow((short) 3);
row1.createCell(0).setCellValue("Asset Number");
row1.createCell(1).setCellValue("Asset Barcode");
row1.createCell(2).setCellValue("Asset Name");
short i = 4;
Row row2 = sheet.createRow(i++);
row2.createCell(0).setCellValue(as.getCdas());
row2.createCell(1).setCellValue(as.getBcd());
row2.createCell(2).setCellValue(as.getNm());
FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls");
wb.write(fileOut);
fileOut.close();
modelMap.put("success", true);
modelMap.put("rows", obj);
modelMap.put("count", count);
} catch (IOException ex) {
modelMap.put("success", false);
modelMap.put("msg", ex.getMessage());
}
return modelMap;
}
I want to make FileOutputStream fileOut = new FileOutputStream(src + "/Export.xls"); with the path I save in db. so If I want to change the path I just change in db.
I've tried code above but doesnt seems work.
please help me. Thanks :)
I would suggest that use it programmatically...
use
String PathTillProject = System.getProperty("user.dir");
This will give you the system path one level up to src i.e. till your project (I assume your src is just within your project directory). For example if your project name is TestProject then location or src is TestProject/src. Now you can use it like:
String PathTillProject = System.getProperty("user.dir");
FileOutputStream fileOut = new FileOutputStream(PathTillProject + "/src/Export.xls");

Categories