I'm using "Apache POI" to generate Excel report. I've a well designed Excel template. I want to create a report by filling the data into predefined locations of the template. That is to say, I do not want to care about the formats of the report. Is that possible? Could you give me some instructions?
I got my answer. I can use the "Cell Naming" utility in Microsoft Excel and then use the following code to locate the cell and do something.
CellReference[] crefs = this.getCellsByName(wb, cName);
// Locate the cell position
Sheet sheet = wb.getSheet(crefs[0].getSheetName());
Row row = sheet.getRow(crefs[0].getRow());
Cell cell = row.getCell(crefs[0].getCol());
// Write in data
cell.setCellValue(cellRegion.getContent());
"cName" is the cell's name predefined in Microsoft Excel.
You can have a look at jXLS, I think that's what you are looking for.
It takes a Excel as template and you can write a Java app to fill the data:
http://jxls.sourceforge.net/
You can load you template file like any other XLS. And then make the changes you want to the specific cells and write it out into another file.
Some sample code:
Load file
InputStream inputStream = new FileInputStream ("D:\\book_original.xls");
POIFSFileSystem fileSystem = new POIFSFileSystem (inputStream);
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
do stuff
HSSFSheet sheet1 = workBook.getSheetAt (0);
Iterator<Row> rows = sheet1.rowIterator ();
while (rows.hasNext ())
{
Row row = rows.next ();
// do stuff
if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
System.out.println ("Row No.: " + row.getRowNum ()+ " " + row.getCell(0).getNumericCellValue());
HSSFCell cell = row.createCell(0);
cell.setCellValue("100");
}
Write the output to a file
FileOutputStream fileOut1 = new FileOutputStream("D:\\book_modified.xls");
workBook.write(fileOut1);
fileOut1.close();
You may also take a look at Xylophone. This is Java library built on top of Apache POI. It uses spreadsheet templates in XLS(X) format and consumes data in XML format.
Related
I am facing a situation where I have to copy conditional formatting from one excel sheet to another.
This is what I tried;
SheetConditionalFormatting sscf= source.getSheetConditionalFormatting();
SheetConditionalFormatting dscf= destination.getSheetConditionalFormatting();
for(int i=0;i<sscf.getNumConditionalFormattings();i++)
dscf.addConditionalFormatting(sscf.getConditionalFormattingAt(i));
source and destination both are XSSF.
But when I try to open destination sheet, excel showing a message that there are some errors in the sheet and do I want to recover it? If I click yes the sheet opens but conditional formatting are not applying correctly.
After repairing excel is showing a message like;
Excel was able to open the file by repairing or removing the unreadable content
In this case my condition formatting is like If there is a space in a range of cells then background of that cell will be gray
But I can not give it hard coded in my destination sheet(though I don't know whether it is possible or not) because there can be different formatting in source sheet.
Can you please mention if I doing something wrong?
That's how it worked for me:
XSSFWorkbook existingWorkbook = (XSSFWorkbook) WorkbookFactory.create(new File("c:/test1.xlsx"));
XSSFWorkbook brandNewWorkbook = (XSSFWorkbook) WorkbookFactory.create(true);
XSSFSheet existingSheet = existingWorkbook.getSheet("Sheet1");
CTWorksheet ctWorksheet = existingSheet.getCTWorksheet();
List<CTConditionalFormatting> formattingList = ctWorksheet.getConditionalFormattingList();
XSSFSheet sheet = brandNewWorkbook.createSheet("Sheet1");
for (CTConditionalFormatting cf : formattingList) {
CTConditionalFormatting newCf = sheet.getCTWorksheet().addNewConditionalFormatting();
newCf.xsetSqref(cf.xgetSqref());
newCf.setCfRuleArray(cf.getCfRuleList().toArray(new CTCfRule[]{}));
}
CTDxfs dxfs = existingWorkbook.getStylesSource().getCTStylesheet().getDxfs();
brandNewWorkbook.getStylesSource().getCTStylesheet().setDxfs(dxfs);
try (FileOutputStream out = new FileOutputStream(new File("c:/test2.xlsx"))) {
brandNewWorkbook.write(out);
}
I have been testing an application where i have to write a set of results to the excel file, the values are taken from the script. But the problem is that first I have to set the column headings like "Sl No" and "Name" after that I have to print the values against the particular cells. The thing is that am not able to write the results under the particular box.
I am new to apache poi. Can anyone help me with this issue.
Code for setting the excel and headings are shown below,
String FileName = "C://Users//Desktop//filename.xlsx";
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("Distributor");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Sl No");
Cell cell2 = row.createCell(1);
cell2.setCellValue("Name");
FileOutputStream outputStream = new FileOutputStream(new File(FileName));
workBook.write(outputStream);
outputStream.close();
I want to use excel to calculate the cdf of normal distribution by input x into excel and read the output of cdf(x) from excel. The excel can be created and calculated correctly. However java cannot read the result from excel correctly.
Here are the relevant code:
private double cdfxls1(double x) throws IOException{
double cdf=0;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("1");
HSSFRow row = sheet.createRow(0);
HSSFCell input = row.createCell(0);
input.setCellValue(x);
HSSFCell output = row.createCell(1);
output.setCellFormula("NORMDIST(A1,0,1,1)");
wb.setForceFormulaRecalculation(true);
/* Using the FormulaEvaluator, still doesn't work
Cell tempoutput=row.getCell(1);
tempoutput.setCellType(Cell.CELL_TYPE_NUMERIC);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
evaluator.evaluateInCell(tempoutput);
evaluator.evaluateFormulaCell(tempoutput);
System.out.println("tempoutput "+tempoutput.getNumericCellValue());
System.out.println("output "+output.getNumericCellValue());
*/
//Using evaluateall, doesn't work either
// HSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
FileOutputStream fileOut = new FileOutputStream("cdf_cal.xls");
wb.write(fileOut);
fileOut.close();
cdf=output.getNumericCellValue();
return cdf;
}
I tried three methods for recalculating the formula. However, none of them worked. I also tried close and reopen the excel. It doesn't work as well. I also tried to use '.csv' as output file instead of '.xls'. It doesn't work either and the cell in csv file contains the formula. When I opened the spreadsheet created, the formula and value are all correct. However, the java can only output 0, the initial value, to me.
Update:
The error message shows:
Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: NORMDIST
at org.apache.poi.ss.formula.functions.NotImplementedFunction.evaluate(NotImplementedFunction.java:42)
These means the normdist function has not been supported and I need to implement it myself. See the list of function supported here:
http://poi.apache.org/spreadsheet/eval-devguide.html
Is there any way that I just let excel to calculate it and I read the result from excel sheet?
I have an Excel file that has 5 columns having few merged cells, blank cells, dates, and other text information (a normal excel file).
I am reading this file using POI API in java. I am able to convert the file to pdf table using iText jar.
But, the whole format is not copied into the pdf. (e.g., merged cells come into one column, and other formatting or settings are all gone).
A simple pdf table is created.
How do i retain the same format as in excel? (I want exact copy of excel sheet in pdf)
Here is the code that I am using
//First we read the Excel file in binary format into FileInputStream
FileInputStream input_document = new FileInputStream(new File("K:\\DCIN_TER\\DCIN_EPU2\\CIRCUIT FROM BRANCH\\RAINBOW ORDERS\\" + SONo.trim() + "\\" + SONo.trim() + " - Checklist.xls"));
// Read workbook into HSSFWorkbook
HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
// Read worksheet into HSSFSheet
HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);
// To iterate over the rows
Iterator<Row> rowIterator = my_worksheet.iterator();
//We will create output PDF document objects at this point
com.itextpdf.text.Document iText_xls_2_pdf = new com.itextpdf.text.Document();
PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream("K:\\DCIN_TER\\DCIN_EPU2\\CIRCUIT FROM BRANCH\\RAINBOW ORDERS\\" + SONo.trim() + "\\" + SONo.trim() + " - Checklist.pdf"));
iText_xls_2_pdf.open();
//we have 5 columns in the Excel sheet, so we create a PDF table with 5 columns; Note: There are ways to make this dynamic in nature, if you want to.
PdfPTable my_table = new PdfPTable(5);
//We will use the object below to dynamically add new data to the table
PdfPCell table_cell;
//Loop through rows.
while(rowIterator.hasNext())
{
Row rowi = rowIterator.next();
Iterator<Cell> cellIterator = rowi.cellIterator();
while(cellIterator.hasNext())
{
Cell celli = cellIterator.next(); //Fetch CELL
switch(celli.getCellType())
{
//Identify CELL type you need to add more code here based on your requirement / transformations
case Cell.CELL_TYPE_STRING:
//Push the data from Excel to PDF Cell
table_cell = new PdfPCell(new Phrase(celli.getStringCellValue()));
//move the code below to suit to your needs
my_table.addCell(table_cell);
break;
case Cell.CELL_TYPE_NUMERIC:
//Push the data from Excel to PDF Cell
table_cell = new PdfPCell(new Phrase("" + celli.getNumericCellValue()));
//move the code below to suit to your needs
my_table.addCell(table_cell);
break;
}
//next line
}
}
//Finally add the table to PDF document
iText_xls_2_pdf.add(my_table);
iText_xls_2_pdf.close();
//we created our pdf file..
input_document.close(); //close xls
I have attached the excel file as an image
Have you used ExcelToHtmlConverter? It's in 3.13 release of the Apache POI. It has the same usage as WordToHtmlConverter. After converting Excel to HTML you can use iText to convert HTML to PDF. This is a PDF I got by using those tools:
With Apache Tika, you can convert xlsx file to html format and via apache pdfbox you can convert html formatted text to pdf.
I am using Apache POI for writing into .xlsx file. I can write into .xlsx file but I am unable to append new content. How can I append new content in the .xlsx file?
My Code is:
public static void write(){
try {
Workbook[] wbs = new Workbook[]{new XSSFWorkbook()};
Workbook workbook=wbs[0];
org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet();
System.out.println(sheet.getSheetName());
Row row = sheet.createRow(2);
for(int i=0;i<10;i++){
Cell cell=row.createCell(i);
cell.setCellValue("Sun System");
}
FileOutputStream fout=new FileOutputStream("D:/Test.Xlsx");
workbook.write(fout);
fout.close();
} catch (Exception e) {
}
}
The first thing U've to do :
When you're working with Excel 2007 format, its more wise to use XSSF-Implementations, because you've used abstract implementations. Always remember this when using any implementation.
To append to an existing file you need to reach the end of the rows in that particular workbook sheet. This can be achieved by:
int rows = sheet.getPhysicalNumberOfRows(); // or sheet.getLastRowNum();
After that you can create new cells with the XSSF- Implementation classes. For more information refer to this page
You should open the existing file instead of creating a new one if you want to append, see also this stackoverflow question:
Edit existing excel files using jxl api / Apache POI
You are creating a new workbook each time this is run youd want to create a FileInputStream with a file path to the excel file and then use that input stream to get the XSSF workbook you want to edit
FileInputStream fis = new FileInputStream(filePath);
XSSFWorkbook workBook = new XSSFWorkbook(fis);
then in order to get a specific sheet you simply just use the .getSheet or getSheetAt methods that are apart of workBook. then create and set cells