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);
}
Related
I want to extract the actual series data and values from a chart in xls file using Apache POI. Point Values like the pair (15.44956728, 7) as shown below. I managed to extract the title of the chart but could not do it with the needed data. Here is my code:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.usermodel.HSSFChart;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println("Hello, World");
InputStream inp;
try {
inp = new FileInputStream("USRAK_00017_0.xls");
HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(inp));
ExcelExtractor extractor = new ExcelExtractor(wb);
extractor.setFormulasNotResults(true);
extractor.setIncludeSheetNames(true);
String text = extractor.getText();
//System.out.println(text);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFChart[] sheetCharts = HSSFChart.getSheetCharts(sheet);
System.out.println(sheetCharts[0].getSeries()[0].getSeriesTitle());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
A better approach I found is to dump the XLS file to XML content in fods format. Open Office can do this job via the following command:
soffice --headless --convert-to fods USRAK_00017_0.xls
Then you can parse the XML the way you like and parse the part you want to extract from the chart
I am trying to write to Excel using apachee POI. It works when the getrow index is 0 like[getrow(o)]. But changing it other than zero throw nullpointer exception.
package fairfoxchecking;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class writingInExcel {
public static void main(String []args) throws IOException {
File src = new File("D:/Etl_Bug_reporting_Template.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 =wb.getSheetAt(0);
sheet1.getRow(0).createCell(5).setCellValue("cheasdfasdfasck1");
sheet1.getRow(1).createCell(5).setCellValue("cheasdfasdfasck1");
FileOutputStream fout = new FileOutputStream(src);
wb.write(fout);
wb.close();
}
Before you do create a cell, you have to ensure the row is created.
Try something like,
if(sheet1.getRow(rowIndex) == null)
sheeet1.createRow(rowIndex)
sheet1.getRow(rowIndex).createCell(colIndex).setCellValue(stringVal);
As per this , getRow might return null if it is not defined. So you might have to create one before writing.
sheet1.createRow(index)
Check this lib - seems to be nice.
I have two queries as below :-
1) Below is my code to find the total disk space, free and used disk space in my local machine. I want to export these values in a newly created excel sheet under three columns Total Disk Space, Free DiskSpace and UsedDiskSpace.
But in my below code I am able to a create excel sheet under C:\ location but I am not able to set the values of my excel sheet columns to the ones calculated and stored under Total diskspace, FreeDiskSpace and UsedDiskSpace variables. Can anyone suggest me how can I modify my below code to set the excel sheet column values to capacity,Free space and used space variable values etc.
2) How can I convert this code into a .bat executable file so that it can be executed on double click and there is no need to execute the entire code through IDE. Some examples will help!!
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.File;
import java.util.ArrayList;
public class DiskSpace
{
public static void main(String[] args)
{ try{ String filename="C:/NewExcelFile.xls" ;
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
ArrayList alldisk=null;
alldisk=new ArrayList();
alldisk.add("C:");
File drive=null;
long capacity=0,freespace=0, usedspace=0;
for(int i=0;i<alldisk.size();i++)
{
drive = new File(alldisk.get(i).toString());
capacity = drive.getTotalSpace();
freespace = drive.getFreeSpace();
usedspace = capacity - freespace;
HSSFRow rowhead= sheet.createRow((short)0);
rowhead.getCell(1).setCellValue(capacity);
rowhead.createCell((short) 0).setCellValue(capacity);
rowhead.createCell((short) 1).setCellValue(freespace);
rowhead.createCell((short) 2).setCellValue(usedspace);
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
}} catch ( Exception ex ) {
System.out.println(ex);
}
}}
Remove
rowhead.getCell(1).setCellValue(capacity);
line.It gives NullPointerException error and don't use createCell(short) it is deprecated method so please remove short type cast.
Here is my code
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileSystemUtils;
import java.io.File;
import java.util.ArrayList;
public class DiskSpace
{
public static void main(String[] args)
{ try{ String filename="/home/likewise-open/EZDI-DOMAIN/cshah/Desktop/NewExamle.xls" ;
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
ArrayList alldisk=null;
alldisk=new ArrayList();
alldisk.add("/home/likewise-open/EZDI-DOMAIN/cshah/Desktop");
File drive=null;
long capacity=0,freespace=0, usedspace=0;
for(int i=0;i<alldisk.size();i++)
{
drive = new File(alldisk.get(i).toString());
capacity = drive.getTotalSpace();
freespace = drive.getFreeSpace();
usedspace = capacity - freespace;
HSSFRow rowhead= sheet.createRow((short)i);
//rowhead.getCell(1).setCellValue(capacity);
rowhead.createCell(0).setCellValue(capacity);
rowhead.createCell(1).setCellValue(freespace);
rowhead.createCell(2).setCellValue(usedspace);
}
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();} catch ( Exception ex ) {
ex.printStackTrace();
}
}}
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>
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