error while reading .xlsm file - java

I am trying to read a .xlsm file using POI.
My code is:
import java.io.*;
import java.util.List;
import jxl.*;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.read.biff.BiffException;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.*;;
public class ReadExcelSheet {
public static void main(String[] args) throws IOException {
final Workbook wb;
FileInputStream fileIn = new FileInputStream("C:\\Users\\my\\Desktop\\ExcelPORead\\Purchace.xlsm");
wb = WorkbookFactory.create(fileIn); // Error in this line
}
}
and I am getting an error at the line "wb = WorkbookFactory.create(fileIn)", it says to "configure Build Path".
I am using Eclipse and downloaded poi-ooxml-3.5-beta5.jar and add it to the Build path.
But I am not getting what I need to do to make it working.
Kindly suggest me how to remove this error or If you have any better way to read the .xlsm files in Java.
Thanks for your response.
Regards,
Raman

Related

How to read cells from xlsx

I need to read cells from XLSX. I use Apache POI, but I don't know what the mistake is.
This is my code:
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class miniwolfi {
public static void main(String[] args) throws IOException {
File excel = new File("/tmp/table.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
double result = wb.getSheetAt(0).getRow(0).getCell(0).getNumericCellValue();
System.out.println(result);
fis.close();
}
}
And the error
java.io.FileNotFoundException: /tmp/таблица.xlsx (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:157)
at miniwolfi.main(miniwolfi.java:17)
Maybe mistake is the way to XLSX. How can I fix this?
Check if the file is xlsx or xls files first, and you have permissions,
Your error is the file is not found
I would write it as follow and use try-with-resources
File excel = new File("/tmp/table.xlsx");
try(FileInputStream fis = new FileInputStream(excel);){
XSSFWorkbook wb = new XSSFWorkbook(fis);
double result = wb.getSheetAt(0).getRow(0).getCell(0).getNumericCellValue();
System.out.println(result);
}

How to get java program read it's internal path to make it work on every PC

I'm trying to configure path in code to my excel file to make it work on every computer that i have source code on for example:
my actual file is in com/company/resources/DatabaseLogonData.xlsx
but im trying to open it from class that is in com/company/Database/DatabaseConnection.java
I suppose i have to go back somehow to com/company and then go to the Database package but don't know how
package com.company.Database;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.File;
import java.io.IOException;
import java.sql.*;
public class DatabaseConnection {
private static Database localDatabase;
public static void setLocalDatabaseFromFile()
throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(
"C:\\Users\\Wiktor\\IdeaProjects\\mixer\\src\\com\\company\\resources\\DatabaseLogonData.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
Row dataRow = sheet.getRow(1);
localDatabase = new Database(dataRow.getCell(0).getStringCellValue(),
dataRow.getCell(1).getStringCellValue(),
dataRow.getCell(2).getStringCellValue(),
dataRow.getCell(3).getStringCellValue());
}
I want to get path that will work on any pc. Thanks for any feedback !
Use java.nio in order to find out where the code is executed:
public static void main(String args[]) throws Exception {
Path cwd = Paths.get("").toAbsolutePath();
Path parentOfCwd = Paths.get("").toAbsolutePath().getParent();
System.out.println(cwd.toAbsolutePath().toString()
+ " in folder " + parentOfCwd.toAbsolutePath().toString());
}
I don't know if this is best practice for your use case, but you could as well go the way many programs are going and just determine the user.home (see comments below your question), create a folder and store the logs there.

Read excel file from string using Apache POI

I am trying to read an excel file from a string using Apache POI 3.9 without any success. I am not too familiar with java.
Just to clarify, in my program I already have the excel file as a string and I am mocking that behaviour by using the readFile function.
Program:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class Test {
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
public static void main(String[] args) throws IOException, InvalidFormatException {
String result = readFile("data.xlsx", StandardCharsets.UTF_8);
InputStream is = new ByteArrayInputStream(result.getBytes("UTF-8"));
Workbook book = WorkbookFactory.create(is);
}
}
The error I am getting is:
Exception in thread "main" java.util.zip.ZipException: invalid block type
at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:164)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:193)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource$FakeZipEntry.<init>(ZipInputStreamZipEntrySource.java:127)
at org.apache.poi.openxml4j.util.ZipInputStreamZipEntrySource.<init>(ZipInputStreamZipEntrySource.java:55)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:83)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:267)
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:73)
at Test.main(Test.java:28)
Any help would be appreciated.
cheers
So the fix for my problem was
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class Test {
public static void main(String[] args) throws IOException, InvalidFormatException {
byte[] result = Files.readAllBytes(Paths.get("data.xlsx"));
InputStream is = new ByteArrayInputStream(result);
Workbook book = WorkbookFactory.create(is);
}
}
It looks like you're making this way too complicated. Just follow the Apache POI Quick Guide, which suggests reading the file with a FileInputStream. There's no need for reading the bytes into a byte array and using a ByteArrayInputStream.
Use one of the following, copied from the guide:
// Use a file
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
// Use an InputStream, needs more memory
Workbook wb = WorkbookFactory.create(new FileInputStream("MyExcel.xlsx"));
What are you doing? You're reading a binary file into a byte[] and convert it to a String using UTF-8. Later you're converting it back to a byte stream using UTF-8 again. What for? Skip all the steps inbetween:
public static void main(String[] args) throws IOException, InvalidFormatException {
InputStream is = new FileInputStream("data.xlsx");
Workbook book = WorkbookFactory.create(is);
}
This bugged me for a while. None of the suggested fixes worked for me. What did resolve the issue was to add a to the maven-resources-plugin, thus
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<configuration>
<encoding>UTF-8</encoding>
<nonFilteredFileExtensions>
<nonFilteredFileExtension>docx</nonFilteredFileExtension>
<nonFilteredFileExtension>xls</nonFilteredFileExtension>
<nonFilteredFileExtension>xlsx</nonFilteredFileExtension>
</nonFilteredFileExtensions>
</configuration>
</plugin>

retrieving data from jasper file

Hi I am very new to jasper reports. Just have a requirement where i need to retrieve the info from a .jasper file. I am using the below code for that.
But issue is compileReport does not take up the file i have in my local machine and i get a error like
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/digester/Digester
at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:150)
at jasper.test(jasper.java:28)
at jasper.main(jasper.java:40)
I am not sure what is wrong.Is it not able to get my .jasper file? which class is missing?
I am absolutely clueless.
My code is:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import dori.jasper.engine.JRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.view.JasperViewer;
public class jasper {
public static void test() throws FileNotFoundException, net.sf.jasperreports.engine.JRException{
JasperReport report = JasperCompileManager.compileReport("C:\\Users\\Mandakini\\Downloads\\testReport.jasper");
JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String, String>());
// export it!
//File pdf = File.createTempFile("output.", ".pdf");
OutputStream output= new FileOutputStream(new File("F:/catalog.pdf"));
JasperExportManager.exportReportToPdfStream(print,output);
}
public static void main(String args[]) throws FileNotFoundException, net.sf.jasperreports.engine.JRException{
test();
}
}
Thanks
A java.lang.NoClassDefFoundError or ClassNotFoundException should almost always tell you that the class it references is missing from your classpath. In this case, it's org.apache.commons.digester.Digester. You can download the jar containing this class here.
To produce a report, do something like:
JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(yourJasperFilePath);
Map<String, Object> parameters = new HashMap<>();
// set your parameters
Class.forName("com.mysql.jdbc.Driver");
Connection con = ...; // possibly get a connection
byte[] report = JasperRunManager.runReportToPdf(jasperReport, parameters, con); // pass the report, the report parameters, and a connection
// this will fill the byte[] with the produced report
FileOutputStream out = new FileOutputStream(somePath);
out.write(report);
out.close();
As to what kind of report it generates, I'm not sure how you set that. That info might be in the .jasper or .jrxml file.

Reading MS Word 2007 using Java

I am trying to read a Microsoft word file through Java. I have included all the .jar files from Apache poi-3.8-beta1 to my classpath. However, when I try running this, I get the following exception:
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:131)
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:104)
at org.apache.poi.poifs.filesystem.POIFSFileSystem.<init>(POIFSFileSystem.java:138)
at readingmsword07.Main.main(Main.java:27)
Following is my code:
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("C:\\TrialDoc.docx");
POIFSFileSystem fileSystem = new POIFSFileSystem(fis);
org.apache.poi.xwpf.extractor.XWPFWordExtractor oleTextExtractor =
new XWPFWordExtractor(new XWPFDocument(fis));
System.out.print(oleTextExtractor.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using the XWPFWordExtractor since I am trying to read a 2007 word document but for some reason I am unable to figure out the right POI that deals with this.
Any help is much appreciated. Thanks in advance!
~ Woods
remove the line,
POIFSFileSystem fileSystem = new POIFSFileSystem(fis);

Categories

Resources