I am very new to java. I am creating pList from excel. My excel file contains multiple sheets. I want to iterate through all the sheets of the excel file. How to to this? please help.
public static void main( String [] args ) {
try {
InputStream input = POIExample.class.getResourceAsStream( "qa.xls" );
POIFSFileSystem fs = new POIFSFileSystem( input );
HSSFWorkbook wb = new HSSFWorkbook(fs);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
HSSFSheet sheet = wb.getSheetAt(i);
// Do your stuff
}
} catch ( IOException ex ) {
ex.printStackTrace();
}
}
From the apache poi documentation we see there is also an iterator available, which is in my opinion a cleaner solution:
Iterator<Sheet> sheetIterator = workbook.iterator();
while (sheetIterator.hasNext()) {
Sheet sheet = sheetIterator.next();
}
Depending on the type of workbook you use (HSSF or XSSF) you might need to execute an additional cast operation:
HSSF: POI Project's pure Java implementation of the Excel '97(-2007) file format.
HSSFSheet sheet = (HSSFSheet) sheetIterator.next();
XSSF: POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
XSSFSheet sheet = (XSSFSheet) sheetIterator.next();
Java:
Workbook workbook = WorkbookFactory.create(file);
Iterator<Sheet> sheetIterator;
sheetIterator = workbook.sheetIterator();
while(sheetIterator.hasNext()){
Sheet sheet = sheetIterator.next();
out.println(sheet.getSheetName());
}
Scala:
var iterator = workbook.sheetIterator();
while(iterator.hasNext){
var sheet = iterator.next
println(sheet)
}
Related
I am getting this error:
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 (e.g. XSSF instead of HSSF)
I read throw Google and I found out that I need to use XSSF instead of HSSF because my Excel file is xlsx, but as you see in my maven, I am already using xlsx. Where have I gone wrong please?
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13-beta1</version>
</dependency>
The code the makes the exception is:
POIFSFileSystem fs;
fs = new POIFSFileSystem(new FileInputStream(getFilePath()));
My new code
public void getBColum() {
try {
OPCPackage fs;
fs = new OPCPackage.open(new File(getFilePath()));
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheet("Master column name - Used Car");
XSSFRow row;
CellReference cr = new CellReference("A1");
row = sheet.getRow(cr.getCol());
System.out.println(row.getCell(3));
} catch (FileNotFoundException e) {
if (logger.isDebugEnabled()) {
logger.debug("How can this error be possible? we should have already thrown an exception in the construction");
}
} catch (IOException e) {
logger.error(String.format("Exception in reading the file: %s",
e.getMessage()));
}
}
I have a compile error in new oPCPackage.open which is:
OPCPackage.open cannot be resolved to a type
According to the Apache POI Quick Guide, the POIFSFileSystem (or similarly, NPOIFSFileSystem) is only used with .xls (Excel versions through 2003) documents.
The equivalent for .xlsx documents (Excel 2007+) is OPCPackage.
OPCPackage pkg = OPCPackage.open(new File("file.xlsx"));
You can create an XSSFWorkbook from the OPCPackage:
XSSFWorkbook wb = new XSSFWorkbook(pkg);
Or you can just create it directly:
XSSFWorkbook wb = new XSSFWorkbook(new File("file.xlsx"));
Generally it's better to create the workbook using a File instead of an InputStream, to save memory.
Also, if you want code that doesn't care whether it's an .xls or an .xlsx:
// or "file.xlsx"
Workbook wb = WorkbookFactory.create(new File("MyExcel.xls"));
I was using XSSF with a xlsx file, but got this error when I tried to process a file that was encrypted/protected with a password.
Once I removed the password, everything worked as expected.
well actually there is no OPCPackage,
I am using https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml/3.5-beta5
so you have to:
import org.apache.poi.openxml4j.opc.Package;
....
Package fs = Package.open(new ByteArrayInputStream(container.getContent()));
XSSFWorkbook wb = new XSSFWorkbook(fs);
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
I want to export all the data from one workbook to another using Java. I used FOR LOOP to read all the data from the input.xls file. Then I want to Export all the read data to output.xls. I don't know how to export it after reading data. I need your help guys. Thanks.
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("C:\\input.xls"));
FileOutputStream wbML = new FileOutputStream("C:\\output.xls");
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
String sValue = cell.getRichStringCellValue().getString();
System.out.println(sValue);
}
}
If you just want to copy the workbook, there is no need to iterate. Just write it to a new file.
Workbook wb = new HSSFWorkbook(new FileInputStream("C:\\input.xls"));
FileOutputStream fileOut = new FileOutputStream("C:\\ouput.xls");
wb.write(fileOut);
fileOut.close();
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"));
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
I have used POI to read from / write to excel sheets.When writing to a new sheet using POI,it worked.But, when i am trying to write in a existing excel workbook using POI, it doesnt worked.how can i correct this issue?
workBook = getWorkbookSheet(workBookName);
sheet1 = workBook.getSheetAt(1);
sheet2 = workBook.getSheetAt(2);
while(sheetStart<sheet1.getLastRowNum() + 1)
{
HSSFRow rowSheet1 = sheet1.getRow(sheetStart);
HSSFCell cellSheet1 = rowSheet1.getCell(4);
if(cellSheet1.getStringCellValue().trim().equals(valY))
{ cellSheet1.setCellValue("N");
}
else
//do nothing
sheetStart++;
}
fileOutSheet1 = new FileOutputStream(sheet1.getSheetName());
workBook.write(fileOutSheet1);
fileOutSheet1.flush();
fileOutSheet1.close();
fileOutSheet1 = new FileOutputStream(sheet1.getSheetName()); seems not correct. you should give the path of workbook instead of sheet1.getSheetName. because you are writing the whole workbook even after a single cell content change.
for example it should be like
FileOutputStream fileOut = new FileOutputStream("C:\\MyWorkbook.xlsx");
wb.write(fileOut);
fileOut.close();
for detail visit here