Trying to read Excel data using java - java

import java.io.*;
import jxl.*;
import jxl.write.*;
class Exc
{
public static void main(String args[])
{
InputStream input = new FileInputStream("sample.xls");
POIFSFileSystem fs = new POIFSFileSystem(input);
Workbook wb = WorkbookFactory.create(input);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(10);
if (cell == null)
cell = row.createCell(10);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("Data");
FileOutputStream fileOut = new FileOutputStream("sample.xls");
wb.write(fileOut);
fileOut.close();
}
}
This is simple code where I am just replacing the data in a cell. When i execute it I get this error:
Exc.java:13: error: cannot find symbol Workbook wb = WorkbookFactory.create(input);
What does the error mean? I have placed the jxl.jar file in the correct path and executed. Thanks in advance.

WorkbookFactory is not a JExcel API class. It belongs to Apache POI.
So, instead of this
InputStream input = new FileInputStream("sample.xls");
POIFSFileSystem fs = new POIFSFileSystem(input);
Workbook wb = WorkbookFactory.create(input);
Use JExcel API's Workbook.getWorkbook() method as
Workbook wb = Workbook.getWorkbook(new File("sample.xls"));

Related

editing an excel sheet using Apache poi

i am trying to edit an excel sheet using apache poi,
I have a worksheet having 2 rows and 5 columns
if second cell of row 2 is null then it should add a 3rd row ,
but i am getting a class not found exception, although the UpdateXLS is present in my D drive.
Here is the code:
public class New {
public static void main(String[] args){
try{
InputStream inp = new FileInputStream("D:\\UpdateXLS.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(2);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
wb.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
}
}
What should i do ?
From the comment , I can suggest you that check file exits on the path specified.
Use File
File f = new File("D:\\UpdateXLS.xls");
//check whether file exists or not to avoid any further exceptions
if(f.exists()){
Workbook wb = WorkbookFactory.create(f);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
......
.......
........
}
FileNotFoundException
Signals that an attempt to open the file denoted by a specified pathname has failed.
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist.
It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
When you are writing a file check your path
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
Change to
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");
The problem seems to be at
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
try to replace the line with:
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");

Null pointer exception while using Apache POI

I am trying to write a excel file using Apache POI package. Here is the code snippet:
String basePath = "/home/aman/Desktop";
String fileName = "result.xls";
File file = new File(basePath, fileName); //File not null. checked.
OPCPackage pkg = OPCPackage.openOrCreate(file); //pkg not null. checked.
Workbook wb = new XSSFWorkbook(pkg); //GenerateReport.java:63
I get the following error:
Exception in thread "main" java.lang.NullPointerException
at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:382)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:186)
at amazon.category.database.GenerateReport.generateExcel(GenerateReport.java:63)
at amazon.category.database.MerchantAdoptionStats.processAdoptionStats(MerchantAdoptionStats.java:197)
at amazon.category.database.MerchantAdoptionStats.main(MerchantAdoptionStats.java:386)
Any help appreciated.
I found this example at the tutorial site:
here
You could try this approach.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
I hit my head against this one for a while myself. The trick is whether or not the file exists prior.
//if file is .xls
Workbook workbook;
if(file.exists) {
NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
workbook = new HSSFWorkbook(fs.getRoot(), false);
}
else {
workbook = new HSSFWorkbook();
}
//if file is .xlsx
Workbook workbook;
if(file.exists) {
OPCPackage pkg = OPCPackage.open(file);
workbook = new XSSFWorkbook(pkg);
}
else {
workbook = new XSSFWorkbook();
}
The trick appears to be (and this doesn't look like it is documented well), that you create the workbooks off of the file system or package objects only if the file exists prior. If you want a new file, then don't use the file system or package objects to create your workbooks.
If everything is what it looks like, you should not be able to build an XSSFWorkbook on an .xls file, since it is a class to model .xlsx files. You should use WorkbookFactory.create() instead of that, which is a factory method that will return the appropiate Workbook implementation for each case

Read xlsx file with POI (SXSSFWorkbook)

I'm trying to do my first tests of reading large xlsx file with POI, but to do a simple test with a small file I fail to show the value of a cell.
Someone can tell me what is my mistake. All the suggestions are welcome. Thanks.
Test.java:
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws Throwable {
File file = new File("/tmp/test.xlsx");
OPCPackage pkg = OPCPackage.open(new FileInputStream(file.getAbsolutePath()));
XSSFWorkbook xssfwb = new XSSFWorkbook(pkg);
SXSSFWorkbook wb = new SXSSFWorkbook(xssfwb, 100);
Sheet sh = wb.getSheet("Hola");
System.out.println("Name: "+sh.getSheetName()); // Line 19
System.out.println("Val: "+sh.getRow(1).getCell(1).getStringCellValue()); // Line 20
}
}
Result:
Name: Hola
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:20)
test.xlsx:
Please consult: similar question SXSSFWorkBook is write only, it doesn't support reading.
For low memory reading of .xlsx files, you should look at the XSSF and SAX EventModel documentation : Gagravarr
If memory wouldn't be an issue you could use a XSSFSheet instead e.g.
File file = new File("D:/temp/test.xlsx");
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sh = wb.getSheet("Hola");
System.out.println(sh.getLastRowNum());
System.out.println("Name: "+sh.getSheetName());
Row row = sh.getRow(1);
System.out.println(row.getRowNum());
System.out.println("Val: "+sh.getRow(1).getCell(1).getStringCellValue());
I too faced the same issue of OOM while parsing xlsx file...after two days of struggle, I finally found out the below code that was really perfect;
This code is based on sjxlsx. It reads the xlsx and stores in a HSSF sheet.
// read the xlsx file
SimpleXLSXWorkbook = new SimpleXLSXWorkbook(new File("C:/test.xlsx"));
HSSFWorkbook hsfWorkbook = new HSSFWorkbook();
org.apache.poi.ss.usermodel.Sheet hsfSheet = hsfWorkbook.createSheet();
Sheet sheetToRead = workbook.getSheet(0, false);
SheetRowReader reader = sheetToRead.newReader();
Cell[] row;
int rowPos = 0;
while ((row = reader.readRow()) != null) {
org.apache.poi.ss.usermodel.Row hfsRow = hsfSheet.createRow(rowPos);
int cellPos = 0;
for (Cell cell : row) {
if(cell != null){
org.apache.poi.ss.usermodel.Cell hfsCell = hfsRow.createCell(cellPos);
hfsCell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
hfsCell.setCellValue(cell.getValue());
}
cellPos++;
}
rowPos++;
}
return hsfSheet;

Apache POI set selected cell after xls document opens

We have next situation: our system has data export in xls format, this is huge file with many rows and columns.
And after user download and open document he see document scrolled to last column and last Spreadsheet tab. This is very annoying, better to set focus on first tab and first cell. I did simple test code to see how it works:
public class SelectionTest {
public static String file = "/usr/test/poi.test/src/main/resources/test";
#Test
public void test() throws FileNotFoundException, IOException {
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet s = wb.getSheetAt(0);
s.setActive(true);
HSSFRow row = s.getRow(0);
HSSFCell cell = row.getCell(0);
cell.setAsActiveCell();
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
}
}
And this doesn't works.
Here is working solution, have found this here
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet s = wb.getSheetAt(0);
wb.setActiveSheet(0);
s.showInPane(0, 0);
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
This worked for me:
sheet.setActiveCell(new CellAddress(0, 0));

shiftRows in apache poi not working

InputStream inp = new FileInputStream("workbook.xls");
HSSFWorkbook wb = new HSSFWorkbook(inp);
String text="";
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
// Do something here
ExcelExtractor extractor = new ExcelExtractor(wb);
text=extractor.getText();
System.out.print("text="+text);
}
}
sheet1.shiftRows(0,sheet1.getLastRowNum(),1);
I am not getting the result in my excel sheet after the shiftrows is called. the data stays the same. Where am I doing it wrong?
This is because you're workbook is only open for reading since it came from an inputstream
InputStream inp = new FileInputStream("workbook.xls");
To get the result you would have to write the new workbook object out to a new xsl spreadsheet. Something like...
File outWB = new File("workbook2.xls");
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
You could do this to the same file but you would need to inp.close() first.

Categories

Resources