Quantcast
Channel: Java Programming Forum - Learn Java Programming - Apache POI
Viewing all 120 articles
Browse latest View live

replace place holder in header and footer


replaceText of usermodel.Range class works on Windows but not on MAC

$
0
0
My project takes a Word template and replaces placeholders with values from a Lotus Notes document. It is currently using LotusScript (VBA) to do this in Windows which means it is using OLE. OLE does not work on the MAC platform so am trying to get Apache POI to do the same thing on the MAC. I have found code to do this called "InsertText.java" and "ParagraphText.java" that does exactly what I need and works fine on the Windows platform. But when I try it on the MAC platform the replaceText method of t he usermodel.Range class gives the following error:
method replacetext(String, String, int) is undefined for the type paragraph
I am running this using the Eclipse IDE on both Windows and MAC and am using Apache POI version 3.13. The "import org.apache.poi.hwpf.usermodel.Range;".

Is there a reason it works on Windows and on the MAC platform?

Import Excel: How to get a blank, when the result of a formula is blank?

$
0
0
Hello,

I am trying to read an excel file via poi. Everything works fine except one thing. In my imported file there are two sheets. Some cells on the first page refers via a formular to cells on sheet 2, for example
Code:

=Sheet2!U3
. I only import sheet 0 and take the values from cells like this:
Code:

final ForumaleEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
final DataFormatter formatter = new DataFormatter();
final String value = formatter.format( cell, evaluator );

If Sheet2!U3 is empty, I always get "0" as value. After debugging I found out why:
WorkbookEvaluator.derefenceResult():
Code:

public static ValueEval dereferenceResult( ValueEval evaluationResult, int srcRowNum, int srcColNum )
{
    ...
    if ( value == BlankEval.instance ) {
        return NumberEval.ZERO;
        // Formulas never evaluate to blank. If a formula appears to have evlautated to blank,
        // the actual value is empty string. This can be verified with ISBLANK().
    ...
}

Is there any possibility to change this behaviour? What is about the method ISBLANK()? I could not find it anywhere? It also would be helpful, if I have access to the returned ValueEval (to do something like this:
Code:

if ( value == NumberEval.ZERO ) return null;
). But as I have seen the ValueEval is wasted during the format()-operation and only the number value of NumberEval is evaluated.

How to create multiple AutoFilter at different rows using Apache POI

$
0
0
Hii,

I want to create AutoFilters at multiple places in an excel sheet using Apache POI. (e.g. at row 2 & at row 8).

Code:

hssfSheet.setAutoFilter(new CellRangeAddress(2, 4, 6, 3));
hssfSheet.setAutoFilter(new CellRangeAddress(8, 5, 3, 5));

I've been adding it like mentioned above but second filter is overriding the first one and when excel sheet is created I can see only one.
Can someone help me.

Thanks.

How to create charts in Word using POI in Java

$
0
0
Hi,

Can some one please help me out in creating charts in Word using POI in java

Regards,
Chennu

Read a spreadsheet to Array, in Excel

$
0
0
I am new to Apache POI and JAVA. Can someone help me by giving me an example of how I would read an Excel sheet and store it as a multi-dimensional array?

Thanks!

Apache poi event api issues

$
0
0
Hi i am developing the app conversion of xlsx/xls to csv using apache poi event api.I am facing some issue please clarify .

For accounting column

While reading from xlsx :
format index is = 44
format string is =_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)
output is coming correct = $ 20.00

but while reading from xls:
format index is = 44
format string is =_(* #,##0.00_);_(* (#,##0.00);_(* "-"??_);_(@_)
output is coming wrong= * 20.00

Can u tell why it is coming wrongly.

typeface font family precedence

$
0
0
I'm hitting some font/tofu problems using the POI library to render a PNG image from XSLFSlide, and it looks to be a latin/ea/cs precedence issue (or lack thereof). Specifically, it appears as though POI 3.15 in the XSLFTextRun.getFontFamily() method is *ONLY* looking for the <latin typeface="foo"> elements, and ignoring the <ea> and <cs> typeface elements. This is a problem for some PPTX files I'm converting, which have 'ambiguous' typeface declarations.

To wit, a pptx slide (from the pptx zip archive: ppt/slides/slide1.xml):

Quote:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<p:cSld>
...yadda...
<p:txBody>

<a:p>
<a:pPr>
<a:lnSpc>
<a:spcPct val="100000"/>
</a:lnSpc>
</a:pPr>
<a:r>
<a:rPr lang="en-US" sz="2800">
<a:solidFill>
<a:srgbClr val="44546a"/>
</a:solidFill>
<a:latin typeface="Comic Sans MS"/>
<a:ea typeface="宋体"/>
</a:rPr>
<a:t>B</a:t>
</a:r>
<a:r>
<a:rPr lang="en-US" sz="2800">
<a:solidFill>
<a:srgbClr val="44546a"/>
</a:solidFill>
<a:latin typeface="Comic Sans MS"/>
<a:ea typeface="宋体"/>
</a:rPr>
<a:t>.书对桌面的压力与桌面对书的支持力</a:t>
</a:r>
<a:endParaRPr/>
</a:p>
</p:txBody>
...etc...
Here the <a:t> text of the second <a:r> text run is definitely NOT comic sans, and that text run is specifying both <a:latin> and <a:ea> elements. In this case, the font family would necessarily be the "宋体" font, but, as I referenced, the XSLFTextRun.getFontFamily() only considers the <a:latin> elements.

for completeness, i'm using the POI library to render the png essentially like this:

Quote:

org.apache.poi.xslf.usermodel.XSLFSlide slide = ...
java.awt.BufferedImage image = new java.awt.BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
java.awt.Graphics2D graphics2D = image.createGraphics();
slide.draw(graphics2D);
javax.imageio.ImageIO.write(image, "PNG", new File("/tmp/sad_panda"));
Doing some digging on the microsoft forums, I ran across this gem: https://social.msdn.microsoft.com/Fo...=os_binaryfile

which eventually states:
Quote:

>>I guess this is the question. How do you figure out weither it's latin/ea/cs from the characers? Is it just looking for a particular set of codepages based on all the text, some of the text, or something else? Is it mulitple codepages?

...We use UNICODE sub ranges + some Windows APIs to decide this....

perhaps reading too much into that msdn post, but it definitely reads to me like there needs to be more logic around the POI 'XSLFTextRun.getFontFamily()' call. At a minimum it needs to look for the 'ea' or 'cs' elements if 'latin' is not present, but preferable there should be some sort of java.awt.Font.canDisplay() or java.awt.Font.canDisplayUpTo() call to ensure the text run text can be rendering using a specified font.

To throw some gas on the fire, the pptx file renders correctly (ie, sans tofu) in libre office, but I haven't gone digging through that codebase to determine how they are determining the correct font.

rfc

ROW Duplication

$
0
0
Background:
1500 columns ( calendar of ca. 3 years = ~1500 days)
1000 rows

in Total ~1.5 Mio cells

ROW = 0
skip

ROW = 1
I am creating for row=1, 1500 columns, i.e. 1500 cells
Each cell is empty.
I am just changing the bg-color.
- Weekend cells are grey background
- Weekdays cells are white background.

So far so good! If I save the Excel file, I got what I need.

ROW = 2...1000 HELP
Now I wanna apply this for the next 1000 rows aswell.
But WHAT is the fastest way to do this?

I tried followinig copy-approach, but not successfully: :(doh):

Code:

final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy();
defaultCopyPolicy.createBuilder();
       
defaultCopyPolicy.setCondenseRows(false);
defaultCopyPolicy.setCopyCellFormula(false);
defaultCopyPolicy.setCopyCellStyle(true);
defaultCopyPolicy.setCopyCellValue(false);
defaultCopyPolicy.setCopyHyperlink(false);
defaultCopyPolicy.setCopyMergedRegions(false);
defaultCopyPolicy.setCopyRowHeight(false);
defaultCopyPolicy.setMergeHyperlink(false);
       
for (int j = 2; j <=1000; j++) {           
        sheet.copyRows(1, 1, j, defaultCopyPolicy);               
}

The for-loop takes 45 seconds.
Afterwards it freezes during saving the file:
Code:

FileOutputStream out = new FileOutputStream(new File(targetFile));
                       
workbook.write(out);
out.close();

WHAT is the fastest way to do this?

(Taskmanager shows 2GB)

typeface font family precedence

$
0
0
I'm hitting some font/tofu problems using the POI library to render a PNG image from XSLFSlide, and it looks to be a latin/ea/cs precedence issue (or lack thereof). Specifically, it appears as though POI 3.15 in the XSLFTextRun.getFontFamily() method is *ONLY* looking for the <latin typeface="foo"> elements, and ignoring the <ea> and <cs> typeface elements. This is a problem for some PPTX files I'm converting, which have 'ambiguous' typeface declarations.

To wit, a pptx slide (from the pptx zip archive: ppt/slides/slide1.xml):

Quote:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<p:cSld>
...yadda...
<p:txBody>

<a:p>
<a:pPr>
<a:lnSpc>
<a:spcPct val="100000"/>
</a:lnSpc>
</a:pPr>
<a:r>
<a:rPr lang="en-US" sz="2800">
<a:solidFill>
<a:srgbClr val="44546a"/>
</a:solidFill>
<a:latin typeface="Comic Sans MS"/>
<a:ea typeface="宋体"/>
</a:rPr>
<a:t>B</a:t>
</a:r>
<a:r>
<a:rPr lang="en-US" sz="2800">
<a:solidFill>
<a:srgbClr val="44546a"/>
</a:solidFill>
<a:latin typeface="Comic Sans MS"/>
<a:ea typeface="宋体"/>
</a:rPr>
<a:t>.书对桌面的压力与桌面对书的支持力</a:t>
</a:r>
<a:endParaRPr/>
</a:p>
</p:txBody>
...etc...
Here the <a:t> text of the second <a:r> text run is definitely NOT comic sans, and that text run is specifying both <a:latin> and <a:ea> elements. In this case, the font family would necessarily be the "宋体" font, but, as I referenced, the XSLFTextRun.getFontFamily() only considers the <a:latin> elements.

for completeness, i'm using the POI library to render the png essentially like this:

Quote:

org.apache.poi.xslf.usermodel.XSLFSlide slide = ...
java.awt.BufferedImage image = new java.awt.BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
java.awt.Graphics2D graphics2D = image.createGraphics();
slide.draw(graphics2D);
javax.imageio.ImageIO.write(image, "PNG", new File("/tmp/sad_panda"));
Doing some digging on the microsoft forums, I ran across this gem: https://social.msdn.microsoft.com/Fo...=os_binaryfile

which eventually states:
Quote:

>>I guess this is the question. How do you figure out weither it's latin/ea/cs from the characers? Is it just looking for a particular set of codepages based on all the text, some of the text, or something else? Is it mulitple codepages?

...We use UNICODE sub ranges + some Windows APIs to decide this....

perhaps reading too much into that msdn post, but it definitely reads to me like there needs to be more logic around the POI 'XSLFTextRun.getFontFamily()' call. At a minimum it needs to look for the 'ea' or 'cs' elements if 'latin' is not present, but preferable there should be some sort of java.awt.Font.canDisplay() or java.awt.Font.canDisplayUpTo() call to ensure the text run text can be rendering using a specified font.

To throw some gas on the fire, the pptx file renders correctly (ie, sans tofu) in libre office, but I haven't gone digging through that codebase to determine how they are determining the correct font.

rfc

ROW Duplication

$
0
0
Background:
1500 columns ( calendar of ca. 3 years = ~1500 days)
1000 rows

in Total ~1.5 Mio cells

ROW = 0
skip

ROW = 1
I am creating for row=1, 1500 columns, i.e. 1500 cells
Each cell is empty.
I am just changing the bg-color.
- Weekend cells are grey background
- Weekdays cells are white background.

So far so good! If I save the Excel file, I got what I need.

ROW = 2...1000 HELP
Now I wanna apply this for the next 1000 rows aswell.
But WHAT is the fastest way to do this?

I tried followinig copy-approach, but not successfully: :(doh):

Code:

final CellCopyPolicy defaultCopyPolicy = new CellCopyPolicy();
defaultCopyPolicy.createBuilder();
       
defaultCopyPolicy.setCondenseRows(false);
defaultCopyPolicy.setCopyCellFormula(false);
defaultCopyPolicy.setCopyCellStyle(true);
defaultCopyPolicy.setCopyCellValue(false);
defaultCopyPolicy.setCopyHyperlink(false);
defaultCopyPolicy.setCopyMergedRegions(false);
defaultCopyPolicy.setCopyRowHeight(false);
defaultCopyPolicy.setMergeHyperlink(false);
       
for (int j = 2; j <=1000; j++) {           
        sheet.copyRows(1, 1, j, defaultCopyPolicy);               
}

The for-loop takes 45 seconds.
Afterwards it freezes during saving the file:
Code:

FileOutputStream out = new FileOutputStream(new File(targetFile));
                       
workbook.write(out);
out.close();

WHAT is the fastest way to do this?

(Taskmanager shows 2GB)

CellRange - color

$
0
0
Hi,

I can set a style for 1 cell, such

Code:

XSSFCell cell = sheet.getRow(0).createCell(0);
cell0.setCellStyle(my_defined_style);

BUT, how do I do this for certain cellrange, such

start_row=1
end_row=1

start_column=10
end_column=20


Thanks, Kalem

conditional formatting does not work on copied cells

$
0
0
Hi everyone!

I am copying cells (value and cellstyle) from one workbook to another,
using the code below.
Now i have two xlsx files, where src.xlsx is the source - where the values are copied from - and the
second one is dst.xlsx.

The dst.xlsx has conditional formatting, e.g. the cells of the first column are "green" if the value is "1" (numeric).

The problem is, the copied cells are not formatted automatically anymore.
That means, the copied cell in column one has the value "1" but is not green (at least not in excel, in libreoffice it is).
It's easy to fix it by hand: Simply select the cell, right click, select filling options and click on the already selected "automatic" or "none".
Afterwards, the cell is correctly displayed in green.

The reason for this behaviour seems to be the following:
POI creates a new FillStyle:

Code:

<patternFill>
<fgColor indexed="64"/>
<bgColor indexed="64"/>
</patternFill>

even if a cell is set to NONE by:

Code:

CellUtil.setCellStyleProperty(newCell, CellUtil.FILL_PATTERN, FillPatternType.NO_FILL);
The correct (or at least "working") solution would be to set the cell to the predefined (fillId=0):
Code:

<fill>
<patternFill patternType="none"/>
</fill>

Excel seems to apply conditional formatting only to two sorts of cells:
1) Those who have the "default" fillstyle - that means fillId=0
2) Those, who have set the fillstyle to: patternType="solid">

Looks like a bug in POI, or at least in Excel... right?
Any suggestions for a workaround? What I need is a way to set the FillStyle (only) to the default one (fillId=0)

Greetings, Flo


Code:

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public class copyHelper{

    private final XSSFSheet srcSheet;
    private final XSSFSheet dstSheet;

  public copyHelper(XSSFSheet srcWorksheet, XSSFSheet dstWorkheet){

        this.srcSheet = srcWorksheet;
        this.dstSheet = dstWorkheet;
    }
   
    public void copyMergedRegions(){

        List<CellRangeAddress> rgLst = srcSheet.getMergedRegions();
        for(CellRangeAddress rg : rgLst)
            dstSheet.addMergedRegion(rg);
    }
           

    public void copyRow(int srcRowNum, int dstRowNum) {
       
        // Get the srcSheet row at srcRowNum
        // and the dstSheet row at dstRowNum
        XSSFRow srcRow = srcSheet.getRow(srcRowNum);
       
        // If the row doesn't exist in the destination worksheet, create
        if(dstSheet.getRow(dstRowNum) == null)
            dstSheet.createRow(dstRowNum);
       
        XSSFRow dstRow = dstSheet.getRow(dstRowNum);

        // Loop through srcSheet columns to add to new row
        for (int i = 0; i < srcRow.getLastCellNum(); i++) {
           
            // Grab a referencing copy of the old/new cell
            XSSFCell oldCell = srcRow.getCell(i);
            XSSFCell newCell = dstRow.createCell(i);

            // If the old cell is null jump to next cell
            if (oldCell == null) {
                newCell = null;
                continue;
            }

            // Copy style from old cell and apply to new cell
            // TODO: Do not copy each and every CellStyle since that leads to
            //      some sort of CellStyle explosion
            //            XSSFCellStyle newStyle = dstSheet.getWorkbook().createCellStyle();
            //            newStyle.cloneStyleFrom(oldCell.getCellStyle());     
            //            newCell.setCellStyle(newStyle);
           
            Map<String, Object> prop = new HashMap<>();
            prop.put(CellUtil.ROTATION, oldCell.getCellStyle().getRotation());
            CellUtil.setCellStyleProperties(newCell, prop);
           
 
            // If there is a cell comment, copy
            if (oldCell.getCellComment() != null)
                newCell.setCellComment(oldCell.getCellComment());

            // If there is a cell hyperlink, copy
            if (oldCell.getHyperlink() != null)
                newCell.setHyperlink(oldCell.getHyperlink());

            // Set the cell data type
            newCell.setCellType(oldCell.getCellType());

            // Set the cell data value
            switch (oldCell.getCellType()) {
                case Cell.CELL_TYPE_BLANK:
                    newCell.setCellValue(oldCell.getStringCellValue());
                    break;
                case Cell.CELL_TYPE_BOOLEAN:
                    newCell.setCellValue(oldCell.getBooleanCellValue());
                    break;
                case Cell.CELL_TYPE_ERROR:
                    newCell.setCellErrorValue(oldCell.getErrorCellValue());
                    break;
                case Cell.CELL_TYPE_FORMULA:
                    newCell.setCellFormula(oldCell.getCellFormula());
                    break;
                case Cell.CELL_TYPE_NUMERIC:
                    newCell.setCellValue(oldCell.getNumericCellValue());
                    break;
                case Cell.CELL_TYPE_STRING:
                    newCell.setCellValue(oldCell.getRichStringCellValue());
                    break;
            }
        }
    }
}

How to identify date cell type using XMLStreamReader (poi's XSSFReader api)

$
0
0
I have a simple excel sheet(.xlsx) with a number of rows. For one of cell the data type is "Date" and I can see the date in correct format in Excel. But when I read excel using XMLStreamReader(poi's XSSFReader api) I get some double value for this cell.

I need to be able to:

1. determine data type of cell

2. if it is date data type then I want to convert the double value to date, as i am not sure which cell is of type date

How can I do this?

Page break in .docx

$
0
0
Hello!
I parse the word file and want to identify page break.
I try to use method "XWPFParagraph.isPageBreak()", but it always returns false.
Code:

sample = new XWPFDocument(new FileInputStream(samplePath));
           
            List<XWPFParagraph>  paragraphs = sample.getParagraphs();

            for (XWPFParagraph par: paragraphs
                ) {
                System.out.println(par.isPageBreak());

            }

Why can I solve this problem? Maybe I use method wrong or other ways to identify page break exist?

Creating Numbered Headings to a Paragraph in Word Document using APACHE POI

$
0
0
Hello Everyone ,

In writing to a word document using Apache poi , for the places where dynamically a paragraph has to get replicated based on some "count" , the headings for those paragraphs has to be numbered sequentially as per the section . Say if it is the 7th Section in the word document , then the headings for each paragraph in it should be numbered in 7.1 , 7.2 and so on sequentially .

Though there are certain solutions which I saw , where the xml of the word document was taken into account and XWPFNumbering was used .

Could there be some other easier way of doing it ?

OR

What if I have word template that already has a paragraph with a numbered heading and I have to replicate the same multiple times ? Does there exists any solution to it ?

How can I do to justify a text in a paragraph?

$
0
0
Good day.

I'm using Apache POI 3.15 version in order to create a Microsoft Word document in Java.
I cannot found a way in order to justify a text in a paragraph.
In XWPFParagraph class I found only BOTH (of ParagraphAlignment class), but with it, if the are a few words in a line it adds several spaces between the words and this is very wrong.
How can I do to make it?

Best regards.

Stefano Errani

Reading Data from *.msg Files - Problem by receiving Email Address of "From"

$
0
0
Hello

i just wrote a small java programm which collects all data from a *.msg (Stored Email File) and writes it to a Excel sheet. Iam using Apache - Poi (might be version 3.15)

My problem right now is that:

Code:

public java.lang.String getDisplayFrom()
                                throws ChunkNotFoundException

Gets the display value of the "FROM" line of the outlook message This is not the actual address that was sent from but the formated display of the user name.

This function only returns the user name / nickname. But i would like to get the Email adress - any suggestions how to deal with it?

Btw: to receive the Email Adress of all recipients you can use getRecipientEmailAddress().

best regards
thanks in advance

Apache POI - Insert HTML content into word document

$
0
0
Is there any way to paste / insert HTML content into word document by using Apache POI API.? Thanks.

Read range name from Excel

$
0
0
Hi Guys,

I am total newbe but i have to know how to read named range in apache poi.

I am trying only to read value for named range.

I am using code like:

Code:

        public static void main(String[] args) throws IOException {
               
               
       
            // setup code
                      String cname = "TestName";
           
            org.apache.poi.ss.usermodel.Workbook wb = null;
                try {
                        wb = WorkbookFactory.create(new File("C:\\Users\\admin\\Desktop\\Example Variable3.xlsm"));
                } catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
               
                int namedCellIdx = wb.getNameIndex("TestVariable");
               
                System.out.println(namedCellIdx);
            org.apache.poi.ss.usermodel.Name aNamedCell = wb.getNameAt(namedCellIdx);
           
            System.out.println(aNamedCell);

            }

        }

and my error is :

Quote:

Exception in thread "main" java.lang.IllegalArgumentException: Specified name index -1 is outside the allowable range (0..0).
Can you help me how to fix this ?

Best,
Jacek
Viewing all 120 articles
Browse latest View live