Even though I have imported
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
I am getting error at part
Iterator<Cell> cellIterator=row.cellIterator();
Here is my full code
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
//import org.apache.poi.hssf.record.formula.functions.Cell;
//import org.apache.poi.hssf.record.formula.functions.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class UploadExcel {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Documents and Settings\\admin\\Desktop\\imp data\\howtodoinjava_demo.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator=row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The error which i am getting is:
Type mismatch: cannot convert from java.util.Iterator<org.apache.poi.ss.usermodel.Cell> to java.util.Iterator<org.apache.poi.hssf.record.formula.functions.Cell>
Could you please help me with this.
You also need this dependency for xssf:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.7</version>
</dependency>
If you don't get compile errors now it means you have this dependency from somewhere else, likely your RiverBoat project exposes an older/incompatible version. So either you need both poi dependencies in this pom, or none (as both may be exposed by RiverBoat).
Related
i'm trying for the first time the apache poi library to manage Execel files. I follow this steps to import apache poi: Import Apache POI in Intellij for JAVA.
The code compile without error but when i run it give me this error messages:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject
at Test.main(Test.java:16)
Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
... 1 more
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\Huawei\\IdeaProjects\\untitled\\src\\TEST.xlsx");
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> itr = sheet.iterator();
while(itr.hasNext()){
Row row = itr.next();
Iterator<Cell> celliterator = row.cellIterator();
while(celliterator.hasNext()){
Cell cell = celliterator.next();
switch (cell.getCellType()){
case STRING: //field that represents string cell type
System.out.print(cell.getStringCellValue() + "\t\t\t");
break;
case NUMERIC: //field that represents number cell type
System.out.print(cell.getNumericCellValue() + "\t\t\t");
break;
default:
System.out.println("NOT NUMERIC AND NOT STRING");
}
}
}
}catch (Exception e ){
e.printStackTrace();
}
}
}
This seems like a classic Maven Project with a .jar downloaded not installed via mvn command.
If ClassNotFoundException raises in runtime, its because your project can't find the library after compiled.
Is this the case? If so, you must add the .jar via mvn install and declare him in your pom.xml. A better solution it's just adding the maven dependency directly:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
My intention is to set the border for the contents of the spreadsheet data while maintaining the other properties of the cell as it is.
The below code formats(setting border) the whole spreadsheet rather than formatting only the portion of spreadsheet where there is actual data.
Is there a reason why the formatting is applied throughout the spreadsheet? And is there a way to overcome this?
package learning.selenium.self.begining;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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;
public class testing {
public static void main(String[] args) throws Exception {
File myFile = new File("TestFile.xlsx");
Workbook myWorkbook = WorkbookFactory.create(new FileInputStream(myFile));
Sheet mySheet = myWorkbook.getSheetAt(0);
Iterator<Row> r = mySheet.rowIterator();
while (r.hasNext()) {
Row myR = r.next();
Iterator<Cell> c = myR.cellIterator();
while (c.hasNext()) {
Cell myC = c.next();
System.out.println("precessing (" + myR.getRowNum() + "," + myC.getColumnIndex() + ")");
CellStyle s = myC.getCellStyle();
s = myC.getCellStyle();
s.setBorderBottom(BorderStyle.THIN);
s.setBorderTop(BorderStyle.THIN);
s.setBorderLeft(BorderStyle.THIN);
s.setBorderRight(BorderStyle.THIN);
myC.setCellStyle(s);
}
}
FileOutputStream fos = new FileOutputStream(myFile);
myWorkbook.write(fos);
fos.close();
}
}
I dont know if this helps but is worth checking out
CellRangeAddress range= new CellRangeAddress(firstrow, lastrow, firstcol, lastcol);
RegionUtil.setBorderBottom(BorderStyle.THIN, range, sheet);
Same way u can set for other borders.
package apsel5;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class A {
public static void main(String[] args) throws Exception{
FileInputStream f = new FileInputStream("D:\\LeadSuite.xlsx");
XSSFWorkbook wbks = new XSSFWorkbook(f);
Sheet s = (Sheet) wbks.getSheet("TestSteps");
Iterator itr = s.iterator();
while(itr.hasNext()){
Row rowitr = (Row)itr.next();
Iterator cellitr = rowitr.cellIterator();
while(cellitr.hasNext()){
Cell cell1= (Cell)cellitr.next();
switch(cell1.getCellType()){
case Cell.CELL_TYPE_STRING:
System.out.println(cell1.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cell1.getNumericCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cell1.getBooleanCellValue());
break;
}
}
}
}
}
I get an exception after running the above code:
Exception in thread "main" java.lang.ClassCastException:
org.apache.poi.xssf.usermodel.XSSFSheet cannot be cast to
org.apache.poi.sl.usermodel.Sheet
You imported the wrong version of Sheet. Simply turn
import org.apache.poi.sl.usermodel.Sheet;
into
import org.apache.poi.ss.usermodel.Sheet;
that represents the Excel worksheet, and your code should work. No cast should be needed for Sheet, Row and Cell.
If you look at the XSSFSheet class definition, you can see that it implements org.apache.poi.ss.usermodel.Sheet. On the other hand, the org.apache.poi.sl.usermodel.Sheet interface is related with PowerPoint; in fact, according to the Javadoc, it's the
Common parent interface for Slides, Notes and Masters
So .ss. = Excel (XSSF), and .sl. = PowerPoint (XSLF). The fact that these two interfaces have the same name may actually be misleading.
My Requirement is to read data from input excel file and write it in output excel file I am using JAVA 8 AND APACHE POI
During the write process I am changing the date format for a particular column from mm/dd/yyyy to dd/mm/yyyy
With below code its setting current date in excel, I want to set same values of input excel in output excel but with new format defined.
Any help would be really appreciated
Below is Updated code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
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 org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class DateFormatDemo1{
public static void main( String[] args ) throws IOException, InvalidFormatException, ParseException
{
OPCPackage pkg = OPCPackage.open(new File("C:\\DateFormatIssue\\SourceFile\\S.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFSheet sheet = wb.getSheetAt(0); // Create spreadsheet in workbook
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=11;
while(iterator.hasNext())
{
row=iterator.next();
cell= row.getCell(pos-1);
XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
cellStyle.setDataFormat( createHelper.createDataFormat().getFormat("M/dd/yyyy")); // set the format of the date
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
Date d=null;
/** below if block converts dates which are in format d/M/yyyy (15/04/2017) to M/d/yyyy (4/15/2017)**/
if (cell.getCellType() == Cell.CELL_TYPE_STRING)
{
d= sdf.parse(cell.getStringCellValue());
cell.setCellValue(d);
cell.setCellStyle(cellStyle);
}
else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
cell.setCellValue(cell.getNumericCellValue());
}
}
FileOutputStream outFile =new FileOutputStream(new File("C:\\DateFormatIssue\\OutputFile\\output.xlsx"));
wb.write(outFile);
wb.close();
outFile.close();
pkg.close();
}}
I'm trying to export some data into Excel files. For which I'm using POI.
As I understand Cell.setCellType(double) sets the appropriate excel equivalent numeric value. But this doesn't change type of the cell.
Column type when I open the generated excel file is General in the Home tab.
Following is a sample code to test it.
package com.example;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
public class TestExcelMain {
public static void main(String[] args) throws Exception {
System.out.println("started");
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue(3.14159);
workbook.write(new FileOutputStream("Test.xlsx"));
System.out.println("finished");
}
}
Is there any other way available to set the cell type to appropriate type ?
I have also tried Cell.setCellType(Cell.CELL_TYPE_NUMERIC) with exactly same result.
Correct type of cell that I expect is Number.
I also tried using all XSSF classess (code below) as suggested in this post setCellType(HSSFCELL.CELL_TYPE_NUMERIC) is not working in apache poi
package com.example;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestExcelMain {
public static void main(String[] args) throws Exception {
System.out.println("started");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue(3.14159);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
workbook.write(new FileOutputStream("Test.xlsx"));
System.out.println("finished");
}
}
Edit
As answered by Jim Garrison, setting cell style does change the type to number. Following is working code.
package com.example;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestExcelMain {
public static void main(String[] args) throws Exception {
System.out.println("started");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell(0);
cell.setCellValue(3.14159);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
XSSFDataFormat format = workbook.createDataFormat();
XSSFCellStyle style = workbook.createCellStyle();
style.setDataFormat(format.getFormat("0.0"));
cell.setCellStyle(style);
workbook.write(new FileOutputStream("Test.xlsx"));
System.out.println("finished");
}
}
From the Javadoc for setCellValue(double value) (emphasis mine):
value - the numeric value to set this cell to. For formulas we'll set the precalculated value, for numerics we'll set its value. For other types we will change the cell to a numeric cell and set its value.
So no matter what the cell was before, this method changes the cell type to numeric anyway.
Note that "General" has nothing to do with the cell type, and everything to do with the cell format. To change the way a cell displays, use setCellStyle().