Read Apache POI XSSFWorkbook in Aspose cells - java

I'm trying to create excel file with watermark in JAVA.
I'm using below approach:
1. using Apache POI api to create excel workbook
2. consume the poi workbook in aspose cells api for adding watermar.
When i'm trying to consume POI workbook in aspose cell i'm getting error- workbook not expected. Please help, as i'm new to spring/JAVA
PFB my code:
package com.mudassir.exceltest.testExcel;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Picture;
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.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TestExcelApplication {
private static String[] COLUMNs = {"Id", "Name", "Address", "Age"};
private static List<Customer> customers = Arrays.asList(
new Customer("1", "Jack Smith", "Massachusetts", 23),
new Customer("2", "Adam Johnson", "New York", 27),
new Customer("3", "Katherin Carter", "Washington DC", 26),
new Customer("4", "Jack London", "Nevada", 33),
new Customer("5", "Jason Bourne", "California", 36));
public static void main(String[] args) throws IOException {
Workbook workbook = new XSSFWorkbook();
CreationHelper createHelper = workbook.getCreationHelper();
Sheet sheet = workbook.createSheet("Customers");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
// Row for Header
Row headerRow = sheet.createRow(0);
// Header
for (int col = 0; col < COLUMNs.length; col++) {
if(col== 0){
Cell cell = headerRow.createCell(col);
cell.setCellValue(COLUMNs[col]);
cell.setCellStyle(headerCellStyle);
}
else{
Cell cell = headerRow.createCell(col+1);
cell.setCellValue(COLUMNs[col]);
cell.setCellStyle(headerCellStyle);
}
}
// CellStyle for Age
CellStyle ageCellStyle = workbook.createCellStyle();
ageCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("#"));
int rowIdx = 1;
for (Customer customer : customers) {
Row row = sheet.createRow(rowIdx++);
row.createCell(0).setCellValue(customer.getId());
row.createCell(2).setCellValue(customer.getName());
row.createCell(3).setCellValue(customer.getAddress());
Cell ageCell = row.createCell(4);
ageCell.setCellValue(customer.getAge());
ageCell.setCellStyle(ageCellStyle);
}
// read the image to the stream
final FileInputStream stream = new FileInputStream("image.png");
final CreationHelper helper = workbook.getCreationHelper();
final Drawing drawing = sheet.createDrawingPatriarch();
final ClientAnchor anchor = helper.createClientAnchor();
//anchor.setAnchorType( ClientAnchor.MOVE_AND_RESIZE );
final int pictureIndex =
workbook.addPicture(IOUtils.toByteArray(stream), Workbook.PICTURE_TYPE_PNG);
anchor.setCol1( 0 );
anchor.setRow1( 9 ); // same row is okay
anchor.setRow2( 11 );
anchor.setCol2( 2 );
final Picture pict = drawing.createPicture( anchor, pictureIndex );
//pict.resize();
Header header = sheet.getHeader();
header.setCenter("&[pict]");
header.setLeft("Left First Page Header");
header.setRight("Right First Page Header");
sheet.addMergedRegion(new CellRangeAddress(0,0,0,1));
sheet.addMergedRegion(new CellRangeAddress(1,1,0,1));
sheet.addMergedRegion(new CellRangeAddress(2,2,0,1));
sheet.addMergedRegion(new CellRangeAddress(3,3,0,1));
sheet.addMergedRegion(new CellRangeAddress(4,4,0,1));
com.aspose.cells.Workbook workbook1=new com.aspose.cells.Workbook(workbook);
FileOutputStream fileOut = new FileOutputStream("customerstest.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}
Please assist me on how can i consume POI workbook in aspose cell workbook.
Below code statement is not working, rather throwing type mismatch error:
com.aspose.cells.Workbook workbook1=new com.aspose.cells.Workbook(workbook);
Thanks

Well, Aspose.Cells and POI XSSF are different APIs with diverse architectures, both have different objects and attributes. I am not sure one can easily parse one's object in other APIs or may be he cannot do that. Aspose.Cells will read and parse valid Excel workbooks (which should follow MS Excel standards and specifications).
I think you may try to save your workbook to Excel file using POI XSSF APIs and then use Aspose.Cells to read that file. If the output file (by POI XSSF) follows MS Excel standards and specifications then it should be opened fine into MS Excel too. If it is opened fine into MS Excel then surely Aspose.Cells should also load the file fine. If you find any issue where Aspose.Cells could not read the final file, then it is an issue with Aspose.Cells. Otherwise I do not think it is an issue with Aspose.Cells. In short, you can simply save the Excel Workbook (by POI XSSF) to disk (Excel file) or streams first then use Aspose.Cells APIs to load it from disk or streams, it should work fine.
I am working as Support developer/ Evangelist at Aspose.

Related

Issues with assigning a style from one workbook to another while attempting a worksheet copy using POI

I have posed a question for copying Excel worksheet contents to a different workbook using Apache POI, while preserving formatting. I have received a good suggestion, which I have gone ahead and implemented (see below). The idea is to copy from the source worksheet to the destination worksheet, row by row.
Initially I got the following exception:
java.lang.IllegalArgumentException: This Style does not belong to the supplied
Workbook Styles Source. Are you trying to assign a style from one workbook to
the cell of a different workbook?
I have tried to fix it but I am now getting the following exception:
java.lang.IllegalArgumentException: Can only clone from one XSSFCellStyle to
another, not between HSSFCellStyle and XSSFCellStyle
This exception is a little weird because I am not using HSSFCellStyle.
Here is my source code:
import java.io.File;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.CellCopyPolicy;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExternalXSSFSheetCopier {
// Create source and destination workbook objects, given the filenames
XSSFWorkbook srcWorkbook = new XSSFWorkbook(new File(srcFilename));
XSSFWorkbook destWorkbook = new XSSFWorkbook(new FileInputStream(destFilename));
// Destination workbook instantiated differently to get past the following exception:
// org.apache.poi.ooxml.POIXMLException: java.io.EOFException:
// Unexpected end of ZLIB input stream
// As per https://stackoverflow.com/a/54695626
// Instantiate the sheet objects
XSSFSheet srcSheet = srcWorkbook.getSheet(srcSheetname);
XSSFSheet destSheet = destWorkbook.createSheet(destSheetname);
// Instantiate CellCopyPolicy object and set all policies to true
CellCopyPolicy copyPolicy = new CellCopyPolicy();
copyPolicy.setCondenseRows(true);
copyPolicy.setCopyCellFormula(true);
copyPolicy.setCopyCellStyle(true);
copyPolicy.setCopyCellValue(true);
copyPolicy.setCopyHyperlink(true);
copyPolicy.setCopyMergedRegions(true);
copyPolicy.setCopyRowHeight(true);
copyPolicy.setMergeHyperlink(true);
// Iterate over the source sheet, row by row, and copy into the destination sheet
int destRowNum = 0;
for (Row srcRow: srcSheet) {
XSSFRow srcXSSFRow = (XSSFRow) srcRow;
XSSFRow destXSSFRow = destSheet.createRow(destRowNum++);
// Introduced the following block of code, as suggested by
// https://stackoverflow.com/questions/10773961/apache-poi-apply-one-style-to-different-workbooks
// to get past the following exception:
// java.lang.IllegalArgumentException: This Style does not belong to the supplied
// Workbook Styles Source. Are you trying to assign a style from one workbook to the
// cell of a different workbook?
XSSFCellStyle srcStyle = srcXSSFRow.getRowStyle();
XSSFCellStyle destStyle = new XSSFCellStyle(new StylesTable());
destStyle.cloneStyleFrom(srcStyle);
destXSSFRow.setRowStyle(destStyle);
// With this block of code we now get the following exception:
// java.lang.IllegalArgumentException: Can only clone from one XSSFCellStyle to
// another, not between HSSFCellStyle and XSSFCellStyle
destXSSFRow.copyRowFrom(srcXSSFRow, copyPolicy);
}
// Final cleanup
srcWorkbook.close();
FileOutputStream fos = new FileOutputStream(new File(destFilename));
destWorkbook.write(fos);
destWorkbook.close();
fos.close();
}

How to properly use style format in apache-poi?

I am trying to format my excel generated file from my java code. This is what my code snippet looks like:
...
Row row = sheet.createRow(rowNum++);
CellStyle textCellStyle = workbook.createCellStyle();
if (rowNum % 2 == 0) {
textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
textCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
textCellStyle.setFont(textFonts1);
} else {
textCellStyle.setFont(textFonts2);
}
cell = row.createCell(0);
cell.setCellValue(student != null ? student.getIdNumber() : "");
cell.setCellStyle(textCellStyle);
...
My expectation was all even rows will be filled with green background but the produced output was different, instead it produced black background. I already tried different color or even changing my fill pattern but i always get black.
I am using poi-3.17 and poi-ooxml-3.17, excel 2007 and java 1.6
You have set a fill pattern for the cell as FillPatternType.SOLID_FOREGROUND. But you did not set a foreground color. This means that the standard color (black) is used as the foreground color.
Try to exchange...
textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
... with ...
textCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
... and it should render as you expect. The text in the cells should also be visible.
It seems counterintuitive to set a foreground color and fill pattern when you want to set a background though.
I'm an Apache POI newbie and don't know much about the details yet. But—in some circumstances—what follows may be useful to you.
This code...
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CellBackground {
public static void main(String[] args) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
int rowNum = 0;
for (FillPatternType fpt : FillPatternType.values()) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
XSSFCellStyle textCellStyle = wb.createCellStyle();
textCellStyle.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
textCellStyle.setFillPattern(fpt);
cell.setCellValue(fpt.name());
cell.setCellStyle(textCellStyle);
sheet.createRow(rowNum++).setHeightInPoints(7);
}
sheet.autoSizeColumn(0);
OutputStream fileOut = new FileOutputStream("CellBackground.xlsx");
wb.write(fileOut);
wb.close();
}
}
...will produce this output in LibreOffice Calc (Apache POI 4.0.1):

Java apache poi: excel cell color

I'm trying to change the background of a cell with apache poi.
I know there are a lot of answers about this, but I'm using the lastest version, (3.16) and they are all deprecated.
For example all the answers suggest that I use
CellStyle#setFillPattern(CellStyle.SOLID_FOREGROUND);
but it's deprecated entirely.
So, following the apache docs, I replaced all the deprecated functions with the new ones and came up with this MCVE:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Mcve{
public static void main(String[] args) {
//Make workbook and first sheet
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("sheet1");
//Make a style
XSSFCellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillBackgroundColor(IndexedColors.RED.getIndex());
//Fill first line
Row row = sheet.createRow(0);
int i = 0;
while (i < 5) {
Cell cell = row.createCell(i);
cell.setCellValue("TestCell " + i++);
cell.setCellStyle(style);
}
//Write to file
File f = new File("Yourfilepathhere/document.xlsx"); //<-- FILL HERE
try (FileOutputStream out = new FileOutputStream(f)) {
workbook.write(out);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I suggest you paste it in an empty Maven project in your IDE of choice and please add these dependencies to your pom.xml:
https://pastebin.com/CXdViuW5
Now, on the lastest version of Excel, this either prints all-black cells or normal white-background cells, depending on the color.
I have tried several colors and styles, doesn't seem to be working. The text is always there, but the background just won't apply.
What am I doing wrong here guys?
Looks like bug, But you can try setting forground color instead of Background color.
XSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.RED.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
row.getCell(0).setCellStyle(style);
This will set your background color.
You forgot to add
cell.setCellStyle(style);
Hope it helps)
XSSFWorkbook workbook1 = new XSSFWorkbook();
XSSFCellStyle greyBackgroundBold = workbook1.createCellStyle();
greyBackgroundBold.setFont(font);
greyBackgroundBold.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
greyBackgroundBold.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

Locking some Excel Cells/Rows with POI others editable

I have to write an excel File where some rows and Columns are locked and the rest is editable. I know this was asked and answered beofre, but the latest answer is from 2012 and the solution given there doesn't work anymore. Can anyone who worked with this give a solution that works now?
This is the code that was given as solution
String file = "c:\\poitest.xlsx";
FileOutputStream outputStream = new FileOutputStream(file);
Workbook wb = new XSSFWorkbook();
CellStyle unlockedCellStyle = wb.createCellStyle();
unlockedCellStyle.setLocked(false);
Sheet sheet = wb.createSheet();
sheet.protectSheet("password");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("TEST");
cell.setCellStyle(unlockedCellStyle);
wb.write(outputStream);
outputStream.close();
The effect now is a sheet that is locked completely.
You wrote, you'd like to lock certain cells and the default should be unlocked, but your code actually unlocks a given cell.
So I go for your original request and have kind of a quick hack as I haven't found a decent method on a quick view to set a whole range of columns:
import java.io.FileOutputStream;
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.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol;
public class XSSFLockTest {
public static void main(String args[]) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
CellStyle unlockedCellStyle = wb.createCellStyle();
unlockedCellStyle.setLocked(false);
CellStyle lockedCellStyle = wb.createCellStyle();
lockedCellStyle.setLocked(true);
XSSFSheet sheet = wb.createSheet();
CTCol col = sheet.getCTWorksheet().getColsArray(0).addNewCol();
col.setMin(1);
col.setMax(16384);
col.setWidth(9.15);
col.setStyle(unlockedCellStyle.getIndex());
sheet.protectSheet("password");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("TEST");
cell.setCellStyle(lockedCellStyle);
FileOutputStream outputStream = new FileOutputStream("bla.xlsx");
wb.write(outputStream);
outputStream.close();
}
}

exporting tables to excel / word using POI

I want the code to export tables / reports to Excel and Word using POI.
I saw the examples that came with POI but could not understand. Can anyone provide me a small/easy code to do the same.
Seeing as you wanted actual code for using POI. Here is some to do some exporting:
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.StringTokenizer;
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
public class XLSExporter implements Exporter {
/**
* Constructor for XLSExporter
*/
public XLSExporter(){
}
public void exportFile( File f, List o ) throws IOException{
HSSFWorkbook wb = new HSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(f);
HSSFSheet sheet = wb.createSheet();
ListIterator it = o.listIterator();
//Construct the headings
HSSFRow headingsRow = sheet.createRow((short)0);
//Heading format
HSSFFont headingFont = wb.createFont();
headingFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle headingStyle = wb.createCellStyle();
headingStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headingStyle.setFont(headingFont);
HSSFCell headingA = headingsRow.createCell((short)0);
headingA.setCellValue("Heading");
headingA.setCellStyle(headingStyle);
int i = 1;
// Iterate over the rows
while(it.hasNext()){
//Create the row
HSSFRow row = sheet.createRow((short)i);
//Write data
HSSFCell cellRunway = row.createCell((short)0);
cellRunway.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellRunway.setCellValue("Whateva");
cellRunway.setCellStyle(standardStyle);
i++;
}
//Set the column widths where needed
sheet.setColumnWidth((short)1, (short)4000);
wb.write(fileOut); // Write the workbook
fileOut.close();
}
}

Categories