How to resolve XSSFWorkbook cannot be resolved to a type - apache-poi

Code outline of Test annotation:
void test() throws Exception{
String filePath = System.setProperty("user.dir", "https://d.docs.live.net/12e57c5f83beb2a2/Documents/Book1.xlsx");
FileInputStream fileStream = new FileInputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook(fileStream);
XSSFSheet sheet = workbook.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
}
I'm trying to read the data from an xlsx file and that when I'm trying to create an Instance of the XSSFWorkbook, the compiler says
"- XSSFWorkbook cannot be resolved to a type"
Please help me how to solve this issue. It Would be really helpful.

Imported the below, will solve your issue.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

Related

Excel Sheet names in Apache POI (without "user" model) [duplicate]

I have the following code that I use to get the sheet names of an excel file(.xlsx)
XSSFWorkbook workBookXlsx = new XSSFWorkbook(new FileInputStream(pathToFile));
ArrayList<String> sheetNames = new ArrayList<>();
int numberOfSheets = workBookXlsx.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
sheetNames.add(workBookXlsx.getSheetAt(i).getSheetName());
}
workBookXlsx = null;
The issue I have with the above code is that it takes a lot of memory(~700MB) & a long time(5-6s) to create the XSSFWorkbook for a file of size 9MB. Even setting the workBookXlsx to null doesn't release the memory taken by the javaw(I know gc may or maynot be called & JVM wont release memory just because I have set a variable to null)
I did go through the documentation of Workbook, XSSFWorkbook & from what I understood, there is no method that will help me get the sheet names with low memory imprint.
The one solution I have found is to manually unzip the .xlsx file and read the contents of the .\xl\woorkbook.xml to get the sheet names and the r:id
Is there an API for getting the sheet names in an .xlsx file without large memory imprint?
To show what #Gagravarr probably meant with his comment:
The XSSFReader contains a method XSSFReader.getSheetsData which "Returns an Iterator which will let you get at all the different Sheets in turn. Each sheet's InputStream is only opened when fetched from the Iterator. It's up to you to close the InputStreams when done with each one.". But as often this is not the whole truth. In truth it returns a XSSFReader.SheetIterator which has a method XSSFReader.SheetIterator.getSheetName to get the sheet names.
Example:
import java.io.InputStream;
import java.io.FileInputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import java.util.Iterator;
public class ExcelXSSFGetSheetNamesXSSFReader {
public static void main(String[] args) throws Exception {
OPCPackage pkg = OPCPackage.open(new FileInputStream("Example.xlsx"));
XSSFReader r = new XSSFReader( pkg );
Iterator<InputStream> sheets = r.getSheetsData();
if (sheets instanceof XSSFReader.SheetIterator) {
XSSFReader.SheetIterator sheetiterator = (XSSFReader.SheetIterator)sheets;
while (sheetiterator.hasNext()) {
InputStream dummy = sheetiterator.next();
System.out.println(sheetiterator.getSheetName());
dummy.close();
}
}
pkg.close();
}
}
Conclusion: Currently you cannot work with apache poi only by trusting the API documentation. Instead you must always have a look at the source code.

How to create a new sheet and write some data in the existing excel using selenium java

I tried the below code.
But it overwrite the existing sheet.
File f= new File(System.getProperty("user.dir")+"\\src\\test\\resources\\Exceldata.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet= workbook.createSheet("Sheet4");
HSSFRow row = worksheet.createRow(1);
HSSFCell cell= row.createCell(1);
cell.setCellValue("admin");
enter code here
workbook.write(f);
workbook.close();
Use FileInputStream instead of File and and object of XSSFWorkbook
I hope this function may help you,
public static void write(){
try
{
FileInputStream myxls = new FileInputStream(System.getProperty("user.dir")+"\\src\\test\\resources\\Exceldata.xls" );
HSSFWorkbook studentsSheet = new HSSFWorkbook(myxls);
workbook = new XSSFWorkbook(myxls );
workbook.createSheet(sheetname);
HSSFSheet worksheet = studentsSheet.getSheetAt(0);
a=worksheet.getLastRowNum();
System.out.println(a);
Row row = worksheet.createRow(++a);
row.createCell(1).setCellValue("");
myxls.close();
FileOutputStream output_file =new FileOutputStream(new File(System.getProperty("user.dir")+"\\src\\test\\resources\\Exceldata.xls"));
//write changes
workbook.write(output_file );
studentsSheet.write(output_file);
output_file.close();
System.out.println(" is successfully written");
}
Try calling this function from main maethod,
public static void main(String args[])
{
write();
}
Possible duplicate of Append Data in existing Excel file using apache poi in java and
How to add new sheets to existing excel workbook using apache POI?
I finally found out the solution. i had used poi jar 4.0 in which i could not succeed in writing data. I then downgraded the jar version to 3.14 and i works perfectly

Getting error create null as blank is deprecated in selenium webdriver

I am working on excel reading automation in selenium webdriver. There are some blank cell in excel.
Actually I have create an excel file with some data like username and password and have given some column (username) values as blank. And when I have run the code it show the exception NullPointerExceptions. So I have Create the object of MissingCellPolicy class and pass in the object in cellcount as a second argument with J. But its show the warning message on below line code:
MissingCellPolicy MCP = Row.CREATE_NULL_AS_BLANK;`
.
The field Row.CREATE_NULL_AS_BLANK is deprecated.
Following code is displayed blank for only First Line columns. For example
Coli1 Column2
Manoj Test
Kumar QA
Test
Rahul
Vinit Sumit
Umesh Naresh
Its displayed blank only for First column under the Test blank should be displayed under the QA also.Please help where i have did mistake.
public class ExcelRead {
public static void main(String[] args) throws Exception {
File fObj = new File("C:\\Selenium\\WebDriverWorkspace\\APERIOSuite\\src\\testData\\Login.xlsx");
FileInputStream fis= new FileInputStream(fObj);
XSSFWorkbook wb= new XSSFWorkbook(fis);
XSSFSheet sheetObj= wb.getSheetAt(0);
int rcount = sheetObj.getLastRowNum();
MissingCellPolicy MCP=Row.CREATE_NULL_AS_BLANK;
for(int i=0;i<=rcount;i++){
Row rowObj=sheetObj.getRow(i);
int cellcnt=rowObj.getLastCellNum();
for(int j=0; j<=cellcnt-1;j++){
Cell cellObj=rowObj.getCell(j,MCP);
String cellvalue =cellObj.getStringCellValue();
System.out.println(cellvalue);
I assume you are talking about the POI library 3.15 from Apache. The new way looks like this:
XSSFWorkbook wb = new XSSFWorkbook(fis);
wb.setMissingCellPolicy(MissingCellPolicy.CREATE_NULL_AS_BLANK);
Edited to fit in your example.

Apache POI header error

I am trying to read an xlsx file using Apache POI. Here is my code -
public static void convertFromXlsx(File inputFile, File outputFile) {
StringBuffer bf = new StringBuffer();
FileOutputStream fos = null;
String strGetValue = "";
try {
fos = new FileOutputStream(outputFile);
// XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(inputFile));
org.apache.poi.ss.usermodel.Workbook wb = WorkbookFactory.create(inputFile);
java.io.IOException: Invalid header signature; read 0x0000000000000000, expected 0xE11AB1A1E011CFD0
Please help me understand why this is happening and how it can be fixed.
There were intially 2 sheets in the xlsx file. I have tried with copies of the file - first removing the 2nd sheet and also by copying and pasting the content into a new sheet as text only but both lead to the same error.

How to create a Progress Bar within a cell using apache poi?

I would like to create a progress bar within a Excel-sheet cell. I must use Apache Poi library, but I do not know how to even start. (Something like this, but using the Java library) http://www.tech-recipes.com/rx/35064/excel-2013-create-progress-bars/
I guess I must put a conditional formating, but I do know how it works and I can not find a solution anywhere ... somebody can help me out?
Thanks in advance.
As you suggested, I've used your link to create an example xlsx and simply recreated the necessary xml structures, i.e. open the xlsx file as zip archive and have a look at xl/worksheets/sheet1.xml. Beside the poi-ooxml.jar you'll need the ooxml-schemas-1.1.jar.
(tested with Libre Office 4.0, Excel Viewer 2010, POI 3.10-beta1)
import java.io.FileOutputStream;
import java.lang.reflect.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
public class Databar {
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
for (int i=0; i<4; i++) {
sheet.createRow(i).createCell(0).setCellValue(new int[]{12,38,93,42}[i]);
}
SheetConditionalFormatting cf = sheet.getSheetConditionalFormatting();
XSSFConditionalFormattingRule xcfrule =
(XSSFConditionalFormattingRule)cf.createConditionalFormattingRule("");
Method m = XSSFConditionalFormattingRule.class.getDeclaredMethod("getCTCfRule");
m.setAccessible(true);
CTCfRule cfRule = (CTCfRule)m.invoke(xcfrule);
cfRule.removeFormula(0); // cleanup
cfRule.setType(STCfType.DATA_BAR);
CTDataBar databar = cfRule.addNewDataBar();
CTCfvo vfoMin = databar.addNewCfvo();
vfoMin.setType(STCfvoType.NUM);
vfoMin.setVal("0");
CTCfvo vfoMax = databar.addNewCfvo();
vfoMax.setType(STCfvoType.NUM);
vfoMax.setVal("100");
CTColor color = databar.addNewColor();
color.setRgb(new byte[]{(byte)0xFF, 0x00, 0x00, (byte)0xFF});
CellRangeAddress cra[] = {new CellRangeAddress(0, 3, 0, 0)};
cf.addConditionalFormatting(cra, xcfrule);
FileOutputStream fos = new FileOutputStream("databar-out.xlsx");
wb.write(fos);
fos.close();
}
}

Resources