Generating an xls file from an xml file - java

I am using the below command to convert an xml file to an excel file, but I could not generate the xls file, please advise how to do that?
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.hssf.model.Workbook;
//import nl.fountain.xelem.excel.Workbook;
import nl.fountain.xelem.lex.ExcelReader;
import org.xml.sax.SAXException;
public class XmlToXls11 {
public void XML() throws ParserConfigurationException, SAXException, IOException
{
ExcelReader reader = new ExcelReader();
Workbook xlWorkbook = (Workbook) reader.getWorkbook("c:/book.xml");
}
}

have you tried the XSerializer?
public void writeExcelXmlFile(String fileNameIn, String fileNameOut){
XLDocument xldoc = new XLDocument(fileNameIn);
OutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(fileNameOut));
new XSerializer().serialize(xldoc.getDocument(), out);
out.close();
} catch (XelemException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I guess that it's not possible to write the old xls-binary format with this library.
have a look here:
https://stackoverflow.com/questions/18177870/how-can-i-read-or-write-xls-files-using-java

Related

FileWriter only displays the last line

When I display the variable data using System.out.println(data), it displays the content (all lines) of the "filename.txt".
However, when I use myWriter.write(data), it only writes the last line of the initial file.
My task is to read a file (in this case, filename.txt) and copy its content into a new file (new.txt).
package javaapplication13;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
public class readFile {
public static String data;
public static void main(String[] args) throws IOException{
try{
File myObj = new File("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\filename.txt");
try (Scanner myReader = new Scanner(myObj)) {
do{
data = myReader.nextLine();
}
while (myReader.hasNextLine());
PrintWriter out = new PrintWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt");
myWriter.write(data);
myWriter.close();
out.close();
myReader.close();
}
}
catch (FileNotFoundException e){
System.out.println("An error occurred.");
}
}
}
Every iteration of the loop opens a new writer, and then writes to it, thus overwriting the file. Instead, you should open the writer once, before the loop, and close it once you're done writing. E.g.:
try (FileWriter myWriter = new FileWriter("C:\\Users\\Admin\\Documents\\NetBeansProjects\\JavaApplication13\\src\\javaapplication13\\new.txt")) {
while (myReader.hasNextLine());
myWriter.write(myReader.nextLine());
}
}

When java program write the file using FileOutputStream, same time I paste the file, FileNotFoundException thrown

Let me explain the situation. In Windows OS.
My java program writes the logfile.
Usually It's OK, but when I copying and pasting the logfile(ctrl + c and v),
java throws exception java.io.IOException: java.io.FileNotFoundException: C:\log.txt (The process cannot access the file because it is being used by another process)
After I research the problem, I found this exception throws by pasting the file. Not copying.
Please tell me why this exception occur.
Reproduce code is below(encode "Windows-31J" is japanese, there is no
particular meaning). Excecute this program and copy and paste "C:\log.txt".
package test;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.stream.IntStream;
public class FileNotFound {
public static void main(String[] args) {
IntStream.range(0, 100000).parallel().forEach(
i -> {
try {
fileWrite("C:\\log.txt", String.valueOf(i));
} catch (IOException e) {
e.printStackTrace();
}
}
);
}
public static void fileWrite(String filePath, String str) throws IOException {
try (FileOutputStream fw = new FileOutputStream(filePath, true);
OutputStreamWriter ow = new OutputStreamWriter(fw, "Windows-31J");
BufferedWriter bw = new BufferedWriter(ow);
PrintWriter out = new PrintWriter(bw)) {
out.println(str);
} catch (IOException e) {
throw new IOException(e);
}
}
}
It occurs because another process, i.e. your Explorer window, is using the file, via the 'copy' action, which Windows does not allow. Solution: don't.

file cannot be deleted even after closing streams

I'm trying to open a file from a URL, copy it to a temporary file, and then delete the temporary file when processing work is done. However, I am unable to delete the file. I have tried closing all streams, I have tried deleting with both deleteOnExit() method and the Delete() method. This is an excel file which I am working with. When I am not using an excel file, or more particularly the Workbook object as shown in my code below, the file deletes just fine. As soon as I pass my file to the workbookFactory.create() method, my file cannot be deleted by the code.
Here's the code below:
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
Workbook wb = WorkbookFactory.create(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.getAbsolutePath());
inputStream.close();
fileoutputStream.close();
System.out.println("Deleted testWB?!" + URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
All the imports I am using:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
I suspect it has something to do with the workbookFactory.create() method, as deletion becomes impossible once I have passed the file to this method.
What am I doing wrong here?
UPDATE. I have come across a fix:
You can pass the File to a FileInputStream, and then pass this stream to the WorkbookFactory.Create() method.
Updated code below to reflect this:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
FileInputStream FIS = new FileInputStream(URLtoFileWriting.destinationFile);
Workbook wb = WorkbookFactory.create(FIS);
FIS.close();
inputStream.close();
fileoutputStream.close();
System.out.println(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I hope this helps.
Find the solution here Close Filehandle for Workbook (apache poi).
Use NPOIFSFileSystem#close() or OPCPackage#close().
For more info have a look at the overloaded constructors of WorkbookFactory class.

Method for FileUpload throwing errors in Java-Windows

I want to test one sample program for file Uploading.But it is showing error "FileNotFoundException".
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestUpload {
/**
* #param args
*/
public boolean handleFileUpload(){
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
boolean isFileUplodedCorrectly = true;
try {
bos = new BufferedOutputStream(new FileOutputStream(new File("D:\\vishu.jpeg")));
bis = new BufferedInputStream(new FileInputStream(new File("D:\\vishuGreetings.jpeg")));
byte[] b = new byte[1024];
while (bis.read(b) != -1)
bos.write(b);
bos.flush();
} catch (Exception e) {
isFileUplodedCorrectly = false;
e.printStackTrace();
System.out.print("Exception in FileUpload Utils " + e);
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return isFileUplodedCorrectly;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
TestUpload tu=new TestUpload();
System.out.println("Status"+tu.handleFileUpload());
}
}
Actually the file is present there. Please Check.
java.io.FileNotFoundException: D:\vishuGreetings.jpeg (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at TestUpload.handleFileUpload(TestUpload.java:23)
at TestUpload.main(TestUpload.java:52)
Exception in FileUpload Utils java.io.FileNotFoundException: D:\vishuGreetings.jpeg (The system cannot find the file specified)Statusfalse
The file D:/vishuGreetings.jpeg is present there.But I am getting a File Not Found Exception for the same.Please check the code provided and revert back.
I solved the problem by giving .jpg instead of jpeg and found it working fine.When I check the properties of the file it is jpeg. that is why I used the extension jpeg in the file nmae in the code.Sorry for the trouble.

how to open .mdb from ftp location jackcess

hi all with this code i can successfully download allpg.mdb and displaying...
now i want to save the downloaded file to c:/folder....
if i edit
dbTempFile = File.createTempFile("dbTempFile",".mdb"); to
dbTempFile = File.createTempFile("c:/dbTempFile",".mdb"); than it give : The filename, directory name, or volume label syntax is incorrect error.
i just want to save the downloaded file to any where to my local drive.
here is code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
public class DownloadFile {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
File dbTempFile=null;
FileOutputStream fileOutputStream = null;
try {
client.connect("ftp.mypak.com");
client.login("myid", "mypwd");
client.setFileType(FTPClient.BINARY_FILE_TYPE);
dbTempFile = File.createTempFile("dbTempFile",".mdb");
fileOutputStream = new FileOutputStream(dbTempFile);
client.retrieveFile("/HASSAN/MDMSTATS/allpg.mdb", fileOutputStream);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("got");
Table table = Database.open(dbTempFile).getTable("items");
System.out.println(table.display());
System.out.println("got");
}
client.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You are not giving the right file name to the Jackcess constructor. should be:
Table table = Database.open(dbTempFile).getTable("items");

Categories