I am trying to create dropdown list in XLS using Apache-poi-3.9 .
Following code I have written ::
public class TestMacroTemplate {
/**
* #param args
* #throws IOException
*/
public static void main(String args[]) throws FileNotFoundException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Data Validation");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0);
DVConstraint dvConstraint = DVConstraint
.createExplicitListConstraint(new String[] { "10", "20", "30" });
DataValidation dataValidation = new HSSFDataValidation(addressList,
dvConstraint);
dataValidation.setSuppressDropDownArrow(false);
sheet.addValidationData(dataValidation);
FileOutputStream fileOut = new FileOutputStream("XLCellDropDown.xls");
try {
workbook.write(fileOut);
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But it gives the following Exception :
Exception in thread "main" java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFSheet.addValidationData(Lorg/apache/poi/ss/usermodel/DataValidation;)V
at ejb.TestMacroTemplate.main(TestMacroTemplate.java:31)
And the same code works with Apache-poi-3.2
Please help me.
Thanks ,
Nirav
Apache POI have a FAQ on this very problem. I'll quote from there, as it'll solve your problem
My code uses some new feature, compiles fine but fails when live with a "MethodNotFoundException", "NoSuchMethodError" or "IncompatibleClassChangeError"
You almost certainly have an older version of POI on your classpath. Quite a few runtimes and other packages will ship an older version of POI, so this is an easy problem to hit without your realising.
The best way to identify the offending earlier jar file is with a few lines of java. These will load one of the core POI classes, and report where it came from.
ClassLoader classloader =
org.apache.poi.poifs.filesystem.POIFSFileSystem.class.getClassLoader();
URL res = classloader.getResource(
"org/apache/poi/poifs/filesystem/POIFSFileSystem.class");
String path = res.getPath();
System.out.println("Core POI came from " + path);
It works fine in Apache poi 3.9 and i have tested it.just incluse these jars
poi-scratchpad-3.9-20121203.jar
poi-3.9-20121203.jar
poi-examples-3.9-20121203.jar
poi-excelant-3.9-20121203.jar
poi-ooxml-3.9-20121203.jar
poi-ooxml-schemas-3.9-20121203.jar
Related
Following code is used:
public static void main(String[] args) throws IOException {
FileInputStream is = new FileInputStream("C:/Users/hp/Downloads/sampPPT.ppt");
HSLFSlideShow ppt = new HSLFSlideShow(is);
is.close();
Dimension pgsize = ppt.getPageSize();
int idx = 1;
for (HSLFSlide slide : ppt.getSlides()) {
BufferedImage img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
// clear the drawing area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
// render
slide.draw(graphics);
// save the output
FileOutputStream out = new FileOutputStream("C:/Users/hp/Downloads/slide-" + idx + ".png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();
idx++;
}
}
This throws following exception:
Exception in thread "main" java.lang.IllegalAccessError: class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl tried to access private field org.apache.poi.POIDocument.directory (org.apache.poi.hslf.usermodel.HSLFSlideShowImpl and org.apache.poi.POIDocument are in unnamed module of loader 'app')
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.readCurrentUserStream(HSLFSlideShowImpl.java:340)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:154)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:127)
at org.apache.poi.hslf.usermodel.HSLFSlideShowImpl.<init>(HSLFSlideShowImpl.java:116)
at org.apache.poi.hslf.usermodel.HSLFSlideShow.<init>(HSLFSlideShow.java:138)
at PPTConv.PPTConv.main(PPTConv.java:27)
To make an answer why such exceptions occur. Maybe it is helpful for others too:
This kind of exception occur if you mix Apache POI jars from different versions. This is not supported. See FAQ.
In that special case there probably are poi-*.jar and poi-scratchpad-*.jar from different versions in classpath. The class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl, which extends org.apache.poi.POIDocument, is contained in poi-scratchpad-*.jar while org.apache.poi.POIDocument is contained in poi-*.jar. If those *.jars are from different versions, then following can occur:
The org.apache.poi.hslf.usermodel.HSLFSlideShowImpl of poi-scratchpad-3.15.jar calls currentUser = new CurrentUserAtom(directory); in code line 340. This is possible because it extends org.apache.poi.POIDocument and this has field protected DirectoryNode directory; in version 3.15 (poi-3.15.jar).
But the same class org.apache.poi.POIDocument of version 3.16 (poi-3.16.jar) has field private DirectoryNode directory;. So if org.apache.poi.hslf.usermodel.HSLFSlideShowImpl of version 3.15 calls currentUser = new CurrentUserAtom(directory); in code line 340, but org.apache.poi.POIDocument is from version 3.16, then java.lang.IllegalAccessError: class org.apache.poi.hslf.usermodel.HSLFSlideShowImpl tried to access private field org.apache.poi.POIDocument.directory is thrown because it really tries to access a private field now.
I use streaming POI API and would like to read the real value of a cell instead of the formatted one. My code which is below works fine but if the user doesn't display all the digit of a value in the excel sheet which is readed by my code, I've got the same truncated value in my result. I didn't find any solution in the streaming API - which is needed in my case to solve memory issue I had using the POI API without streaming.
/**
* #see org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler.SheetContentsHandler cell(java.lang.String,
* java.lang.String)
*/
#Override
void cell(String cellReference, String formattedValue, XSSFComment comment) {
useTheCellValue(formattedValue)
}
If you are constructing the XSSFSheetXMLHandler you can provide a DataFormatter. So if you are creating your own DataFormatter this DataFormatter could give you fully access to the formatting issues.
Example of how this could look like by changing the public void processSheet of the XLSX2CSV example in svn:
...
public void processSheet(
StylesTable styles,
ReadOnlySharedStringsTable strings,
SheetContentsHandler sheetHandler,
InputStream sheetInputStream) throws IOException, SAXException {
//DataFormatter formatter = new DataFormatter();
DataFormatter formatter = new DataFormatter(java.util.Locale.US) {
//do never formatting double values but do formatting dates
public java.lang.String formatRawCellContents(double value, int formatIndex, java.lang.String formatString) {
if (org.apache.poi.ss.usermodel.DateUtil.isADateFormat(formatIndex, formatString)) {
return super.formatRawCellContents(value, formatIndex, formatString);
} else {
//return java.lang.String.valueOf(value);
return super.formatRawCellContents(value, 0, "General");
}
}
};
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(
styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch(ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
...
I've seen a ticket on POI about this point : https://bz.apache.org/bugzilla/show_bug.cgi?id=61858
It provides a first solution by changing the existing class.
This could be an interesting workaround even if the ideal solution should be to use a standard one.
Using NPOI 2.1.3.1, I am trying to read an existing Excel (*.xlsx) workbook, modify it, and then write it back to the original file. After reading various threads (including this one), I still cannot find a solution to the problem I'm having.
When I write the file to disk and then try to open it again in Excel, I get the following error:
We found a problem with some content in (filename. Do you want us to
try to recover as much as we can? If you trust the source of this
workbook, click Yes.
Clicking "Yes" fixes various problems in the Excel file, after which I see the following report of the fixes performed:
Replaced Part: /xl/worksheets/sheet3.xml part with XML error. Illegal
name character. Line 3, column 3891168.
Replaced Part: /xl/worksheets/sheet19.xml part with XML error. Illegal name
character. Line 1, column 699903.
Removed Records: Formula from /xl/calcChain.xml part (Calculation properties)
I unzipped the *.xlsx file and found the sheets mentioned and discovered that the character it was referring to is a bare ampersand (&) that was not written as "&" in the XML. The original does use "&", but the file NPOI wrote does not. I have no idea what the issue is with the formula (third issue).
Here is a complete program that reproduces this issue every single time with the workbook I'm using, with the file name removed:
using System.IO;
using NPOI.XSSF.UserModel;
namespace NpoiTest
{
public sealed class NpoiTest
{
public static void Main(string[] args)
{
XSSFWorkbook workbook;
using (FileStream file = new FileStream(#"C:\Path\To\File.xlsx", FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(file);
}
using (FileStream file = new FileStream(#"C:\Path\To\File.xlsx", FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
workbook.Write(file);
}
}
}
}
As a test, I wrote pretty much the same program using Apache POI, to see if it was just a universal problem with my workbook, and the result was that POI didn't have any problems.
Here is the complete program:
package poitest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class PoiTest
{
public static void main(String[] args)
{
XSSFWorkbook workbook;
try (FileInputStream file = new FileInputStream(new File("C:\\Path\\To\\File.xlsx")))
{
workbook = new XSSFWorkbook(file);
}
catch (IOException e)
{
System.out.println(e.getMessage());
return;
}
try (FileOutputStream out = new FileOutputStream(new File("C:\\Path\\To\\File.xlsx")))
{
workbook.write(out);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
So the question is why is NPOI leaving the bare ampersands? Is this just a bug in NPOI?
public class ReadAndWrite {
public static void main(String[] args) throws InterruptedException, BiffException, IOException
{
System.out.println("hello");
ReadAndWrite.login();
}
public static void login() throws BiffException, IOException, InterruptedException{
WebDriver driver=new FirefoxDriver();
driver.get("URL");
System.out.println("hello");
FileInputStream fi = new FileInputStream("/home/sagarpatra/Desktop/Xpath.ods");
System.out.println("hiiiiiii");
Workbook w = Workbook.getWorkbook(fi);
Sheet sh = w.getSheet(1);
//or w.getSheet(Sheetnumber)
//String variable1 = s.getCell(column, row).getContents();
for(int row=1; row <=sh.getRows();row++)
{
String username = sh.getCell(0, row).getContents();
System.out.println("Username "+username);
driver.get("URL");
driver.findElement(By.name("Email")).sendKeys(username);
String password= sh.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.name("Passwd")).sendKeys(password);
Thread.sleep(10000);
driver.findElement(By.name("Login")).click();
System.out.println("Waiting for page to load fully...");
Thread.sleep(30000);
}
driver.quit();
}
}
I don't know what is wrong with my code, or how to fix it. It outputs the following error:
Exception in thread "main" jxl.read.biff.BiffException: Unable to recognize OLE stream
at jxl.read.biff.CompoundFile.<init>(CompoundFile.java:116)
at jxl.read.biff.File.<init>(File.java:127)
at jxl.Workbook.getWorkbook(Workbook.java:221)
at jxl.Workbook.getWorkbook(Workbook.java:198)
at test.ReadTest.main(ReadTest.java:19)
I would try using Apache MetaModel instead. I have had better luck with that, than using JXL. Here is a example project I wrote that reads from a .XLSX file. I use this library to run tests on a Linux Jenkins server from .XLS files generated on MS Windows.
Also, it should be noted that this library is also perfect for making a parameterized DataProvider that queries a database with JDBC.
Using JXL, you limit yourself to one data type, either .XLS or .CSV. I believe MetaModel is actually using JXL under the hood and wrapping it to make it easier to use. So, it also would support the OpenOffice documents in the same fashion and suffer the same file compatibility issues.
I have recently upgraded my Smooks application from 1.4 to 1.5.1, but I keep getting the exception below:
Error when processing EDI file org.milyn.cdr.SmooksConfigurationException: Error
invoking #Initialize method 'initialize' on class 'org.milyn.smooks.scripting.groovy.GroovyContentHandlerFactory'.
I am pretty new to Smooks and Groovy, but this is an extract of my code, which was working in version 1.4.
I also have all the 1.5.1 classes in my classpath, including the 1.5 EDI definitions I am trying to load.
Smooks smooks = null;
try {
smooks = new Smooks();
}
catch(Exception exception) { System.out.println("Error " + exception); }
try {
smooks.setReaderConfig(new UNEdifactReaderConfigurator("urn:org.milyn.edi.unedifact:d01b-mapping:*"));
// Create an exec context - no profiles....
ExecutionContext executionContext = smooks.createExecutionContext();
DOMResult domResult = new DOMResult();
// Configure the execution context to generate a report...
executionContext.setEventListener(new HtmlReportGenerator("EDI/reports/report.html"));
smooks.filterSource(new StreamSource((InputStream) bufferedinputstream), domResult);
Extract from GroovyContentHandlerFactory
#Initialize
public void initialize() throws IOException {
String templateText = StreamUtils.readStreamAsString(getClass().getResourceAsStream("ScriptedGroovy.ftl"));
classTemplate = new FreeMarkerTemplate(templateText);
Any help or ideas would be much appreciated as I have spent hours on trying to figure this one out.
Cheers, Matt