When I try to add data to Excel from Java Ant, it shows NoClassDefFoundError, even that I imported all Jar files of Apache Poi. This is the Error:
Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/commons/io/output/UnsynchronizedByteArrayOutputStream
This is the code i tried:
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("Sheet1");
XSSFRow row = sheet.createRow(0);
Cell cell0 = row.createCell(0);
cell0.setCellValue("HelloWorld!");
try{
FileOutputStream out = new FileOutputStream(new File("Result.xlsx"));
wb.write(out);
out.close();
System.out.println("Done");
}catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
These are Jar imported files:
Problem solved! It seems i needed to add dependecy to build.xml also after importing jar files!
Related
I'm trying to create a simple Excel file in XLSX format.
I can create the old XLS files but when I try to create the other format, the file is always corrupt.
I'm using Apache POI 4.1.1.
This is my simple code:
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
FileOutputStream fo = new FileOutputStream("C:/Users/Public/invoice_file/Test.xlsx");
try {
wb.write(fo);
fo.flush();
fo.close();
wb.close();
}catch (Exception e) {
e.printStackTrace();
}
And this is the error message: Error
Use
org.apache.poi.ss.usermodel.WorkbookFactory
//Parameter indicates whether you want to create an XSSF formatted file or not
WorkbookFactory.create(true); //true creates XSSF formatted file
will return you an instance of
org.apache.poi.ss.usermodel.Workbook
Then you can write to the file using
Workbook.write(OutputStream)
Solution:
try (Workbook wb = WorkbookFactory.create(true)) {
Sheet sheet = wb.createSheet("new sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Hellooooo");
try (FileOutputStream fos = new FileOutputStream("D:/Test.xlsx")) {
wb.write(fos);
}
}
How to save symbols like 🔥🔥 to xlsx file using Java 8 and Apache POI library?
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet 1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("\uD83D\uDD25\uD83D\uDD25");
try {
FileOutputStream outputStream = new FileOutputStream("text.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
As a result, I get a file with symbols "????" Instead of "🔥🔥".
How to perform different functions on Microsoft Excel spreadsheet using Apache POI ?
I'm trying to generate and update an Excel file ( data from DB ) from my Spring MVC App..
Thanks
Include apache poi jar file
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
To read an excel file
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
The classes we used in above code snippet, HSSFWorkbook and HSSFSheet works for .xls format. In order to work with .xlsx use XSSFWorkbook and XSSFSheet class.
Similar to HSSF, POI has different prefix for other file formats too:
HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.
HPSF (Horrible Property Set Format) – reads “Document Summary” formation from Microsoft Office files.
HWPF (Horrible Word Processor Format) – aims to read and write Microsoft Word 97 (DOC) format files.
HSLF (Horrible Slide Layout Format) – a pure Java implementation for Microsoft PowerPoint files.
HDGF (Horrible DiaGram Format) – an initial pure Java implementation for Microsoft Visio binary files.
HPBF (Horrible PuBlisher Format) – a pure Java implementation for Microsoft Publisher files.
HSMF (Horrible Stupid Mail Format) – a pure Java implementation for Microsoft Outlook MSG files.
DDF (Dreadful Drawing Format) – a package for decoding the Microsoft Office Drawing format.
Create New Excel File
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FuSsA sheet");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Slim Shady");
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Update Existing Excel File
try {
FileInputStream file = new FileInputStream(new File("C:\\update.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Cell cell = null;
//Update the value of cell
cell = sheet.getRow(1).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(2).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
cell = sheet.getRow(3).getCell(2);
cell.setCellValue(cell.getNumericCellValue() * 2);
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
For more details, Adding Formulas and Adding Styles to Cell you can check this link: Read / Write Excel file in Java using Apache POI
For manipulation of any cells or adding formula , you can use the folowing:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Calculate Simple Interest");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Pricipal Amount (P)");
header.createCell(1).setCellValue("Rate of Interest (r)");
header.createCell(2).setCellValue("Tenure (t)");
header.createCell(3).setCellValue("Interest (P r t)");
Row dataRow = sheet.createRow(1);
dataRow.createCell(0).setCellValue(14500d);
dataRow.createCell(1).setCellValue(9.25);
dataRow.createCell(2).setCellValue(3d);
dataRow.createCell(3).setCellFormula("A2*B2*C2");
try {
FileOutputStream out =
new FileOutputStream(new File("C:\\formula.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
For adding styles to the cell,
you can use: cell.setCellStyle(style);
For adding background to cells, you can use the following:
cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
I have a Excel template wich I want to open, modify and save it like a normal book of excel when I click in a button in a Jframe.
This is the code:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
InputStream inp;
try {
inp = new FileInputStream("plantilla.xlt");
XSSFWorkbook wb = new XSSFWorkbook(inp);
XSSFSheet sheet = (XSSFSheet) wb.getSheetAt(1);
XSSFRow row = sheet.getRow(3);
XSSFCell cell1 = row.getCell(1);
XSSFCell cell2 = row.getCell(2);
cell1.setCellValue(0);
cell2.setCellValue(10000);
//FileOutputStream fileOut = new FileOutputStream("plantilla.xlt");
//wb.write(fileOut);
//fileOut.close();
} catch (IOException ioe) {
Logger.getLogger(DonnéesFE.class.getName()).log(Level.SEVERE, null,ioe);
}
}
This is new for me so I have a couple questions:
I have to put the whole file path to get the FileInputStream? Is the extension .xlt correct? Right now it doesn't find the file. I have tried with the normal .xlsx extension and it finds it (I don't think it found the good file either) but I get this error on the definition of the workbook that I don't understand:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException.`
When I finish editing the excel template how I save it as a new excel book? Everybody uses a new file to save the output but I think that won't work here.
try {
File file = new File("file4.xls");
if (!file.exists()) file.createNewFile();
FileInputStream fis = new FileInputStream(file);
POIFSFileSystem fileSystem = new POIFSFileSystem(fis);
// FileInputStream fis = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
//Sheet sheet = workbook.createSheet("sheet0");
Sheet sheet = workbook.getSheet("sheet1");
sheet.createRow(0).createCell(0).setCellValue("HelloWorld");
Cell cell = sheet.createRow(1).createCell(0);
cell.setCellValue("Value_1_1");
fis.close();
FileOutputStream fos = new FileOutputStream(file);
workbook.write(fos);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
I am trying to create simple excel file using java. I am getting above mentioned error.
Open the file once.
Check your file once on click save as. If it is generated from HTML it will show as Web page(*.htm , .html) below drop down to the file.
You can save as Excel 97-2003 Workbook (.xls) and retry to read from code. It worked in my case.
Your problem is this line here:
if (!file.exists()) file.createNewFile();
That creates a brand new 0 byte file, which is not a valid Excel file. That's why POI objects.
Also, you're using an old version of Apache POI. Newer ones give a more helpful exception if you're silly enough to ask them to read a zero byte file
Taking account of the advice on Files vs InputStreams, but noting you're doing an in-place write which isn't yet fully supported on an opened File, change your code to be more like:
Workbook workbook = null;
File file = new File("file4.xls");
if (!file.exists()) {
if (file.toString().endsWith(".xlsx")) {
workbook = new XSSFWorkbook();
} else {
workbook = new HSSFWorkbook();
}
} else {
workbook = WorkbookFactory.create(new FileInputStream(file));
}
That will work for both .xls and .xlsx files, and avoids your errro
Though you really ought to upgrade your version of Apache POI too...