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.
Related
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);
}
Hello Guys I have made a xlsx file in the mentioned location as in figure:
and I have a code as below:-
package com.nischal;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FileRead {
public static void main(String[] args) throws IOException {
File src = new File("D:\\Nischal.xlsx");
FileInputStream fis=new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh1= wb.getSheetAt(0);
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());
}
}
Though there is nothing wrong it always yields the error called: (The system cannot find the file specified)
Image of the Error:
Any suggestions will be helpful
Maybe you need to cast variable name "fis" to string while sending as parameter to XSSFWorkbook;
XSSFWorkbook wb= new XSSFWorkbook(String.valueOf(fis));
The problem was there when I have created a file i.e I have given the file Name is Nischal.xslx but it is not proper format I have to give file name only Nischal and select extension as .xslx. And Now finally it works.
See Now I have changed my renamed my file as
The Working code is same as above.
package com.writeAndRead;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.*;
public class Read {
public static void main(String[] args) throws FileNotFoundException, IOException {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream("excel.xls"));
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
}
if (row.getCell(1).getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
System.out.println(row.getCell(1).getDateCellValue());
}
}
}
error: CELL_TYPE_NUMERIC cannot be resolved or is not a field.
I have tried reducing it to just NUMERIC but I GOT THE SAME PROBLEM.
Hey guys thanks for the comments. I solved the issue myself. The HSSFCell.CELL_TYPE_NUMERIC is now just NUMERIC. Thanks guys.
later version of Apache POI poi-4.0.1 should Change your if condition from HSSFCell.CELL_TYPE_NUMERIC to NUMERIC
like this :
if (row.getCell(1).getCellType() == NUMERIC) {
System.out.println(row.getCell(1).getDateCellValue());
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>