How to save an excel file with .xls extension in java? - java

I have to save an excel file with .xls extension.I want that the extension should be taken by default as soon as I select the file type in save file dialog box designed using file chooser.I have tried this much of code but it is saving the file in .xls format only when I give the file name as filename.xls
public void FileSave() throws IOException{
JFileChooser chooser=new JFileChooser(".");
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files","xls","excel");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setFileSelectionMode(chooser.FILES_AND_DIRECTORIES);
chooser.setDialogTitle("Save File");
chooser.setCurrentDirectory(new File(System.getProperties().getProperty("user.home")));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter(){
public boolean accept(final File f){
return f.isDirectory()|| file.getAbsolutePath().endsWith(".xls");
}
public String getDescription(){
return "Excel files (*.xls)";
}
});
int returnVal1=chooser.showSaveDialog(this);
if (returnVal1 == JFileChooser.APPROVE_OPTION){
file1 = chooser.getSelectedFile();
if(!file1.exists()){
FileOutputStream fileOut = new FileOutputStream(file1);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}
else if(file1.exists()){
int res=JOptionPane.showConfirmDialog(this,"File already exists.Do you wish to overwrite?");
if(res == JOptionPane.YES_OPTION){
FileOutputStream fileOut = new FileOutputStream(file1);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}else if(res == JOptionPane.NO_OPTION){
int returnVal2=chooser.showSaveDialog(this);
if (returnVal2 == JFileChooser.APPROVE_OPTION){
File file2 = chooser.getSelectedFile();
if(!file2.exists()){
FileOutputStream fileOut = new FileOutputStream(file2);
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}
}
}else if (res == JOptionPane.CANCEL_OPTION){
JOptionPane.showMessageDialog(this, "User cancelled operation.");
}
}
}
}

You need to use this option to set the file name as *.xls:
chooser.setSelectedFile("*.xls");
And for the File type dropdown, set the below options:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files","xls","excel");
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
chooser.setAcceptAllFileFilterUsed(false);

I did this and it worked.
if(!file1.exists())
{
FileOutputStream fileOut = new FileOutputStream(file1+".xls");
hwb.write(fileOut);
fileOut.close();
System.out.println("\n Your Excel file has been generated!");
JOptionPane.showMessageDialog(this,"File Created.");
}

Related

Unable to create HSSFWorkbook workbook for a .xls file that is within a ZIP file

My requirement is that there is a .xls file within a zip file, which can be downloaded using an URL. As I want to read this excel file in memory (for later processing), without downloading the zip locally, I have used ZipInputStream and this is how the main part of my code looks like:
String finalUrl = "https://server/myZip.zip"
URL url = new URL(finalUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry file;
try {
while ((file = zis.getNextEntry()) != null) {
if (file.getName().endsWith(".xls")) {
log.info("xls file found");
log.info("file name : {}", file.getName());
byte excelBytes[] = new byte[(int)file.getSize()];
zis.read(excelBytes);
InputStream excelInputStream = new ByteArrayInputStream(excelBytes);
HSSFWorkbook wb = new HSSFWorkbook(excelInputStream);
HSSFSheet sheet = wb.getSheetAt(8);
log.info("sheet : {}", sheet.getSheetName());
}
else {
log.info("xls file not found");
}
}
}
finally{
zis.close();
}
But unfortunately I am receiving the following error:
java.lang.ArrayIndexOutOfBoundsException: Index -3 out of bounds for length 3247
Note:
The .xls file is around 2MB and the zip file does not have any complex structure such as sub-directories or multiple files.
Any help here would be highly appreciated. Thanks!
Thanks to #PJ Fanning for highlighting this,
The problem was in zis.read(excelBytes) which does not guarantee to read all the bytes. After using IOUtils.toByteArrayinstead, the problem was resolved. The correct code is:
String finalUrl = "https://server/myZip.zip"
URL url = new URL(finalUrl);
InputStream inputStream = new BufferedInputStream(url.openStream());
ZipInputStream zis = new ZipInputStream(inputStream);
ZipEntry file;
try {
while ((file = zis.getNextEntry()) != null) {
if (file.getName().endsWith(".xls")) {
log.info("xls file found");
log.info("file name : {}", file.getName());
byte excelBytes[] = IOUtils.toByteArray(zis);
InputStream excelInputStream = new ByteArrayInputStream(excelBytes);
HSSFWorkbook wb = new HSSFWorkbook(excelInputStream);
HSSFSheet sheet = wb.getSheetAt(8);
log.info("sheet : {}", sheet.getSheetName());
}
else {
log.info("xls file not found");
}
}
}
finally{
zis.close();
}

saving a file fiormat pdf file with java

I am trying to create a pdf file then save it to device using fileChooser
It works the saving but when i go to the file to open it it doesn't open
here is my code
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
fc.setTitle("Save to PDF"
);
fc.setInitialFileName("untitled.pdf");
Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();
File file = fc.showSaveDialog(stg);
if (file != null) {
String str = file.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(str);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close();
writer.close();
fos.flush();
}
when i open it this is the error showing it says the file is either opened or used by another user
Your code does not close() the FileOutputStream which may cause a resource leak and the document is not properly accessible, maybe even corrupted.
When you work with a FileOutputStream that implements AutoClosable, you have two options:
close() the FileOutputStream manually:
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF File", "*.pfd"));
fc.setTitle("Save to PDF");
fc.setInitialFileName("untitled.pdf");
Stage stg = (Stage) ((Node) event.getSource()).getScene().getWindow();
File file = fc.showSaveDialog(stg);
if (file != null) {
String str = file.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(str);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(str));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close();
writer.close();
fos.flush();
/*
* ONLY DIFFERENCE TO YOUR CODE IS THE FOLLOWING LINE
*/
fos.close();
}
}
or use a try with resources read about that in this post, for example.

Inserting a pdf file to a database and then downloading it on another computer

So I've managed to insert a pdf file into my database using BLOBS.
now if I would like to retrieve the pdf file on another computer using the same database but on a computer that doesn't have the pdf file downloaded how can I do that?
I would like to have it so that it starts a download for the pdf when a button is pressed.
The code down below I use to insert files into the database.
btnBifogaFiler.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
file.setCurrentDirectory(new
File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new
FileNameExtensionFilter("*.Images", "jpg", "gif", "png", "pdf");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
selectedFile = file.getSelectedFile();
path = selectedFile.getAbsolutePath();
int i = path.lastIndexOf(".");
String nyPath = path.substring(i, i + 4);
lblBild.setText(nyPath);
s = path;
}
}
});
try {
PreparedStatement ps2 = connection.prepareStatement("INSERT INTO
FILER(FILID,FIL,TYP) VALUES (?,?,?)");
InputStream is = new FileInputStream(new File(s));
selectedFile = file.getSelectedFile();
path = selectedFile.getAbsolutePath();
extension = "";
int i = path.lastIndexOf(".");
extension = path.substring(i,i+4);
textLabel.setText(extension);
ps2.setInt(1,nyaVardet2);
ps2.setBlob(2, is);
ps2.setString(3,extension);
ps2.executeUpdate();
}

Create a .zip file in Java with images

I'm creating a Java program which gets images from a JFileChooser and create a .zip file containing the selected images. I get the files with this code:
final JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileFilter(new FileNameExtensionFilter("Image files", "bmp", "png", "jpg"));
fc.setAcceptAllFileFilterUsed(false);
fc.showOpenDialog(null);
File files[] = fc.getSelectedFiles();
How i create a .zip file containing the files of the files[] array?
Thank you for your help :D.
File someFile = new File("someFile.zip");
File files[] = fc.getSelectedFiles();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(someFile));
// Create the ZIP file first
try (ZipOutputStream out = new ZipOutputStream(bos)) {
// Write files/copy to archive
for (File file : files) {
// Put a new ZIP entry to output stream for every file
out.putNextEntry(new ZipEntry(file.getName()));
Files.copy(file.toPath(), out);
out.closeEntry();
}
}

Create ArrayList from JFileChooser instead of hard coded option

I currently access my .csv file via hardcoded ArrayList. I want to be able to select the file, instead of it being hard coded like it is currently.
I just added the JFileChooser. I cannot get get my rowData to read line by line of the file selected through JOptionPane. How do I do this?
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV Files", "csv");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open file: " + chooser.getSelectedFile().getName());
}
my Original Code started here (without the commented line), and it works. I just don't want it hard coded in.
ArrayList<String> rowData = new ArrayList<String>();
FileConnections excelConn = new FileConnections();
//rowData = excelConn.read(chooser);
rowData = excelConn.read(new File("11738 IPACC INFINITY Unconfirmed OIVS Responses.csv"));
Try this (untested btw!):
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("CSV Files", "csv");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
System.out.println("You chose to open file: " + chooser.getSelectedFile().getName());
ArrayList<String> rowData = new ArrayList<String>();
FileConnections excelConn = new FileConnections();
rowData = excelConn.read(chooser.getSelectedFile());
}
Is equivalent to:
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open file: " + chooser.getSelectedFile().getName());
ArrayList<String> rowData = new FileConnections().read(chooser.getSelectedFile());
}

Categories

Resources