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();
}
Related
I have a scenario where first I update an excel column with certain values using one test case (test case 1) and then use that file for upload in the next test case (test case 2). I am able to successfully update the file and also able to browse the file for upload. the problem is that the content is not being read from the file. I just have to open the excel file created and perform the save action manually and then when I run the test (test case 2)related to uploading it works perfectly fine. I am not sure what is causing the issue. it would be of great help if someone can support this issue.
Here are the test steps
Update file column values - code snippet
public void setColValues(String fileName, String sheetName, int colIndex, List<Integer> sData) {
try {
String excelPath = System.getProperty("director to file path");
FileInputStream fis = new FileInputStream(excelPath);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sh = workbook.getSheet(sheetName);
int rowCount = sh.getLastRowNum();
logger.info(rowCount);
int index = 0;
for (int rowCounter = 2; rowCounter <= rowCount; rowCounter++) {
sh.getRow(rowCounter).getCell(colIndex).setCellValue(sData.get(index));
index++;
}
fis.close();
FileOutputStream fos = new FileOutputStream(new File(excelPath), false);
workbook.write(fos);
workbook.close();
fos.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
go to a specific URL
Click the browse button and pass the file path
Click the button to upload
It might be because you are not passing a File instance to FileInputStream constructor?
You wrote:
FileInputStream fis = new FileInputStream(excelPath);
Try instead:
FileInputStream inputStream = new FileInputStream(new File(excelPath));
When I run this code in NetBeans IDE 8.2 it updates the excel file without incident. However when I build the JAR I get the following error when I run this part of the code "java.io.FileNotFoundException: file:\D:\Projects\ht\ht\dist\ht.jar!\HTAlarms_1.xlsx". It reads the excel file just fine, however I am doing something wrong when I am trying to write to the excel file.
public void setAlarmFileContents() {
System.out.println("Inside of setAlarmFileContents");
String fileName = "HTAlarms_1.xlsx";
ClassLoader classLoader = new ht().getClass().getClassLoader();
InputStream is = getClass().getClassLoader().getResourceAsStream(fileName);
try {
Workbook workbook = WorkbookFactory.create(is);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(123);
Cell cell = row.createCell(2);
cell.setCellValue("Testing Data Worked inside of IDE");
is.close();
System.out.println("Input stream is closed");
File file = new File(classLoader.getResource(fileName).getFile());
FileOutputStream outputStream = new FileOutputStream(file);
workbook.write(outputStream);
workbook.close();
outputStream.close();
System.out.println("Streams closed data set?");
} catch (IOException | EncryptedDocumentException ex) {
ex.printStackTrace();
}
}
I'm reading a file, adding some data to paragraphs, and then writing out a document another file.
The problem I'm facing is that the output file is unreadable, I can't open it, and if a binary open it I can see that it don't have the correct format.
Every character has a ? character at the left side.
Can you give me some advice about what is happening?
Wrong output
Correct output
EDIT: Code Save function
FileOutputStream out = null;
try {
// Add true to make the data append possible in output stream.
out = new FileOutputStream(filePath, true);
doc.write(out);
out.flush();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
Edit file:
File file = new File("muestra.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
POIFSFileSystem fs = new POIFSFileSystem(fis);
HWPFDocument document = new HWPFDocument(fs);
Range range = document.getRange();
for (int i = 0; i < document.getParagraphTable().getParagraphs().size(); i++) {
Paragraph p = range.getParagraph(i);
p.insertBefore("£");
}
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").
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.