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

Read Date from Excel and change its Format

$
0
0
Hello,

i have excel file and i want to reat some column and insert it in Db, any way i want to read Column with date
Code:

Date
========
14.12.2010
15.12.2010
16.12.2010
17.12.2010
18.12.2010
19.12.2010
20.12.2010
21.12.2010
22.12.2010

Code:

public class Date_DB {
   
    private String name;
    private Date dateOfCommission;
  //Setters und Getters

Calss To read from Excel
Code:

Date_DB pp = new Date_DB();
pp.setDateOfCommission(row.getCell(12).getDateCellValue());  ///date
set.add(pp);

But it reads the Date as the flowing:
Code:

Tue Dec 14 00:00:00 CET 2010
Wed Dec 15 00:00:00 CET 2010
Thu Dec 16 00:00:00 CET 2010
Fri Dec 17 00:00:00 CET 2010
Sat Dec 18 00:00:00 CET 2010
Sun Dec 19 00:00:00 CET 2010
Mon Dec 20 00:00:00 CET 2010
Tue Dec 21 00:00:00 CET 2010
Wed Dec 22 00:00:00 CET 2010

Now what i wish is to reformat this Date to be exactly like in the Excel file (have Format ""dd.MM.yyyy" ) and store them ad a Date in the Set

I read a lot about Calender Format, but i didn't find any thing really helpful

Any Help?

DateFormatter.formatRawCellContents throwing IllegalArgumentException for 0.0 value.

$
0
0
Hi,

I am trying to read a xlsm file with POI

switch (cell.getCachedFormulaResultType()) {

case Cell.CELL_TYPE_NUMERIC:
double value = cell.getNumericCellValue();
int formatIndex = cell.getCellStyle().getDataFormat();
String formatStr = cell.getCellStyle().getDataFormatString();
formatted = dateFormatter.formatRawCellContents(0.0, formatIndex, formatStr);
break;

}

Whenever there is value 0.0 formatRawCellContents api is throwing IllegalArgument Execption.

Any Idea ?

Thanks
Narayan

HTML to DOCX or DOC

$
0
0
I have report page with images and text. I want to convert it to word document. How can I do this? I'm using Seam 2.2.2.FINAL with JSF (if it helps you)
Images are stored in html in base64, for example:
<p>SOME TEXT <img src='data:image/gif;base64,BYTES' /> CONTINUE TEXT</p>

Read Excel Form Control

$
0
0
Hi,

I want to read the value of checkbox from a excel worksheet using Apache POI. But not able to get the value.

Regards,
Rajesh

DOCX gets corrupted after several opening and closing

$
0
0
Hello,
first of all, sorry about my english. I hope someone could know if there is any problem with my code or it's a problem with poi library. I'm using poi 3.9.

The fact is this:

1.- I read a file with XWPFDocument:

Code:

File docFile = null;
                    docFile = new File(fileUrl);
                    FileInputStream fis;
                        try {
                                fis = new FileInputStream(docFile.getAbsolutePath());
                                XWPFDocument doc = new XWPFDocument(fis);

2.- I do some operations, but I've tried the code withour any code here, so I'll pass.

3.- I write the file into disk:

Code:

FileOutputStream out = new FileOutputStream(outFile);
                                doc.write(out);
                                out.close();

The size of the document get's changed, but this doesn't worry me. The problem is that after several modifications, the size of it are increased each time. At about 14 or 15 "open-close" iterations, the file stucks in this line:

Code:

XWPFDocument doc = new XWPFDocument(fis);
It takes 100% cpu and 100% of available Java memory, until out of memory error is thrown. I think poi modifies the internal structure adding some things to it. If I open the file with Word, and save it, it turns to the beginning state, all ok, but I need to get it modified automatically a lot of times.

Anyone has faced something similar?

Apache POI - Create Password Protected Excel - Read only protected.

$
0
0
I need to create a password protected excel.

Currently, I'm using Apache POI (WriteProtectWorkBook) which unfortunately allows the users to open the excel in Read only mode.

This is not recommended with the data that I'm handling.

Could you please let me know how we can achieve this?

Thanks in advance.

How to write in existing *.xlsx file using java

$
0
0
Hi Guys! This is my first post here. Hope you all are doing well.
Could you please help me how to write to existing xlsx file using java. If you could site an example that would be better
Thanks in advance

Apache POI help needed

$
0
0
Hi,

We have dynamic content to be displayed in excel(xlsx) file. First couple of rows will have table data after table data we need to show text(in merged region). There will not be any limit to the character count.

We used below snippet to create merged cell region
Lets say table rows are 10 and columns are 5 (these are not constants)
XSSFSheet xssfSheet; //valid xssfSheet
int firstRow; //row after table data. table rows + 2, so firstRow will be 12
int lastRow; // firstRow+<...> (we have some custom logic to identify this)
int firstCol; //always 0
int lastCol; // table column size lastCol will be 5, (table columns )
CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
xssfSheet.addMergedRegion(region);

From above snippet lastRow is being calculated using total number of characters and some other stuff and then determining the lastRow value to show content fit to merged region. (sometimes content fits to merged region, sometimes content overflows the region and sometimes content is less and white space appears). I am sure this is not elegant way to do it. I couldn't find any other way.

I need to understand what would be the right way to fit the content in merged region without content overflow or too much white space

Any help would be appreciative

Digital signature on Office documents

$
0
0
Hi

Please, could someone point me in the right direction to digitally sign an Office document (docx, xlsx, pptx) using POI?
I have already reviewed the classes under org.apache.poi.openxml4j.opc.signature but I cannot understand how I could add a signature to a document.
I cannot find any working sample on Internet.

Thanks in advance

How to read value of a checkbox using Apache.POI. (Help please!)

$
0
0
I am using apache POI for the first time.I am trying to read the value of a check-box from a word document(fixed template). But i am not getting the proper values(0 or 1) for unchecked and checked boxes respectively. Could anyone please help me with this? The code that I am using is as follows:

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class DocReader {

public void readDocFile()
{
File docFile = null;
WordExtractor docExtractor = null ;
WordExtractor exprExtractor = null ;
try
{
docFile = new File("c:\\Temp.doc");

FileInputStream fis=new FileInputStream(docFile.getAbsolutePath());

HWPFDocument doc=new HWPFDocument(fis);

docExtractor = new WordExtractor(doc);
}
catch(Exception exep)
{
System.out.println(exep.getMessage());
}


String docArray[] = docExtractor.getParagraphText();

for(int i=116;i<118;i++)
{
if(docArray[i] != null)
System.out.println(docArray[i].trim());
}
}

public static void main(String[] args) {
DocReader reader = new DocReader();
reader.readDocFile();
}
}
---------------------------------------
The output is:

FORMCHECKBOX Option1
FORMCHECKBOX Option2

----------------------------------------

I simply copied the check boxes from the word file and pasted them to a text file and I am getting:

1 Option1
0 Option2

where Option1 is the checked check-box and Option2 is unchecked.
I was hoping to see something similar as the output of my java code.
Could anyone please help?

How to get freeze columns information through apache poi for excel?

$
0
0
I have an excel file in which any column is made freeze by user. Now i want to get information about the freeze columns. How can i do that? Any kind of help is appreciated. I am using apache poi to read excel (.xsl) file.

Unreadable content when creating xlsx file using Apache POI

$
0
0
I am getting the below message when opening a xlsx file generated through Apache POI.

"We found a problem with some content in "workbook.xlsx". Do you want to try to recover as much as we can? If you trust the source of this workbook. click Yes"

If we click yes the excel is recovered but all the validation are removed and I am getting this message "Repaired Part: /xl/worksheets/sheet1.xml part with XML error. Load error. Line 2, column 0."

Attached is the code snippet which I am using.

Can you someone help me here
Attached Files

Reading my excel values

$
0
0
I have an excel worksheet that has macros & formulas. My objectives are to
(1) Read the file from a specific folder, change the value of E6 and force the recalculations on the entire sheet that work off of that cell
(2) Output the file (with a new name) to a different folder with the new calculated cells and values
(3) From the new created file, grab the calculated values from D10 and E10 (these cells have formulas in them) and output them to the screen and a database.

I have accomplished the first two objectives -but I am struggling on the 3rd.
When I try to grab the values, it is giving me the values as if they were from the beginning file before the E6 value was changed and the calculations were forced.

Can someone please help? I'm not sure what I am doing wrong. My code is below:

Code:

FileInputStream file = null;
HSSFWorkbook workbook = null;
HSSFSheet sheet = null;
Cell cell = null;
FileInputStream file2 = null;
HSSFWorkbook workbook2 = null;
HSSFSheet sheet2 = null;
Cell cell2 = null;
FileOutputStream outFile = null;
Double GED_W = 0.0;
Double GED_H = 0.0;
Double GED_A = 0.0;
Double GED_B = 0.0;

file = new FileInputStream(new File("I:\\Specials XLS\\"+productline+"\\"+workbookname+".xls"));
workbook = new HSSFWorkbook(file);
sheet = workbook.getSheet(getsheet);
 
    //Update the value of cell
    cell = sheet.getRow(5).getCell(4);
    cell.setCellValue(userwidth);

workbook.setForceFormulaRecalculation(true);
file.close();

outFile = new FileOutputStream(new File("I:\\ORDERS\\"+productline+"\\ORDER_"+ordernumber+"_ORDERLINE_"+orderlinenumber+"_"+mainproducttype+".xls"));
    workbook.write(outFile);
    outFile.close();

file2 = new FileInputStream(new File("I:\\ORDERS\\"+productline+"\\ORDER_"+ordernumber+"_ORDERLINE_"+orderlinenumber+"_"+mainproducttype+"_"+(java.sql.Date) dt+".xls"));
    workbook2 = new HSSFWorkbook(file2);
    sheet2 = workbook2.getSheet(getsheet);
    cell2 = sheet2.getRow(9).getCell(3);
    GED_W = cell2.getNumericCellValue();
    System.out.println("GED_W CELL VALUE: " + GED_W);
    cell2 = sheet.getRow(9).getCell(4);
    GED_H = cell2.getNumericCellValue();
    System.out.println("GED_H CELL VALUE: " + GED_H);

GED_W & GED_W both give me the incorrect values - they are not giving me the updated data

get Bytes from XSSF workbook

$
0
0
In HSSFWorkbook there is method getBytes(); How can i getBytes from XSSFWorkbook as there is no method?

Your InputStream was neither an OLE2 stream, nor an OOXML stream

$
0
0
I am using Apache Commons to upload a .docx . While uploading, I also want to extract text by using Apache POI libraries.

If I pass the inputstream returned from item.openStream(); from ServletFileUpload to POI API,I get the exception:java.lang.IllegalArgumentException: Your InputStream was neither an OLE2 stream, nor an OOXM

public static String docx2text(InputStream is) throws Exception {
return ExtractorFactory.createExtractor(is).getText();
}

my application server does not allow me to write to file, so I cannot use FileInputStream.

how do I handle this? I am uploading valid .docx file.There are no issues with uploading file.

-regards
Ma

What do I need to close to free memory ?

$
0
0
Hi.

I use poi to read Excel files in a task in Bonita BPM.
When I run this task more than 3 times, it won't work again and I see this error in the log :
org.bonitasoft.engine.connector.exception.SConnect orException: java.util.concurrent.ExecutionException: java.lang.ExceptionInInitializerError

I think it happens because I try to read multiple time in the same file.
I probably need to free memory by closing something in my program but I don't know what.

Here is my code :

Code:

public static Workbook openWorkbook(String nomFichier, String password) {
        try {
            FileInputStream file = new FileInputStream(new File(nomFichier));
            BufferedInputStream bufferInput = new BufferedInputStream(file);
            file.close();
            if (nomFichier.endsWith("xls")) {
                POIFSFileSystem pfs = new POIFSFileSystem(bufferInput);
                Biff8EncryptionKey.setCurrentUserPassword(password);
                bufferInput.close();
                return new HSSFWorkbook(pfs);
            }
            if (nomFichier.endsWith("xlsx")) {
                POIFSFileSystem pfs = new POIFSFileSystem(bufferInput);
                EncryptionInfo encInfo = new EncryptionInfo(pfs);
                Decryptor decryptor = Decryptor.getInstance(encInfo);
                decryptor.verifyPassword(password);
                bufferInput.close();
                return new XSSFWorkbook(decryptor.getDataStream(pfs));
            }
            if (nomFichier.endsWith("xlsm")) {
                OPCPackage pkg = OPCPackage.open(new File(nomFichier));
                bufferInput.close();
                XSSFWorkbook wb = new XSSFWorkbook(pkg);
                pkg.close();
                return wb;
            }
            bufferInput.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Le fichier doit être au format .xls, .xlsm ou .xlsx !");
        return null;
    }

public static ArrayList<String> getListeIdRelease(String nomFichier, String password, String nomOnglet){
        Workbook workbook = openWorkbook(nomFichier, password);
        Sheet sheet = workbook.getSheet(nomOnglet);
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
        Iterator<Row> rowIterator = sheet.iterator();
        TreeSet<String> listeIdRelease = new TreeSet<String>(Collator.getInstance());
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Cell cellRelease = row.getCell(releaseIndex);
            Cell cellEtat = row.getCell(etatIndex);
            if (cellRelease != null && cellEtat.getStringCellValue().equals("")) {
                listeIdRelease.add(getCellValueToString(cellRelease, evaluator));
            }
        }
        return new ArrayList<String>(listeIdRelease);
    }

I already close the file, bufferInput and OPCPackage.
Did you have and idea of what can cause this problem ?

Thanks in advance.

how to tune and optimize POI Code

$
0
0
hi am exporting adf table to excell i what to optimize my code using BigGridDemo.java

how can i do the same using below code

[code]
Code:

public void generateExcel(FacesContext facesContext, OutputStream outputStream) throws IOException {

 
        try {

 
       

 
       
       
       
       
       
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet worksheet = workbook.createSheet("Big Grid");
       
       
       

 
        // Get all the rows of a iterator
        /////////////////////////////////////////////////////////////////////////////////////////////////////

 
        DCBindingContainer bindings = (DCBindingContainer)BindingContext.getCurrent().getCurrentBindingsEntry();
        DCIteratorBinding dcIteratorBindings = bindings.findIteratorBinding("CustomClientView1Iterator");
       
        Row rowss = worksheet.createRow(0);
        ViewObject yourVO= dcIteratorBindings.getViewObject();
        // Get all the rows of a ViewObject
        RowSetIterator iter = yourVO.createRowSetIterator("CustomClient");
        iter.reset();
        int rowCounter = 0;
        while (iter.hasNext()){
        Cell cell = null;
        oracle.jbo.Row row = iter.next();

 
        //print header on first row in excel
        if (rowCounter == 0) {
        rowss = worksheet.createRow(rowCounter);
        int cellCounter = 0;

 
        for (String colName : row.getAttributeNames()) {
        cell = rowss.createCell(cellCounter);
        cell.setCellValue(colName);

 
        // cellA1.setCellValue(colName);

 
        cellCounter++;
        }
        }
        //print data from second row in excel

 
        rowCounter++;
        //////////////////////////////////////////////////////////////
       

 
        int cellCounter = 0;

 
       

 

 
        rowss = worksheet.createRow(rowCounter);
        for (String colName : row.getAttributeNames()) {
        System.out.println("hello "+row.getAttribute(colName));
        System.out.println("hello "+colName);
       
        cell = rowss.createCell(cellCounter);
        rowCounter++;

 
        /// cell.setCellValue(new HSSFRichTextString(rs.getS));
        if(!isBlank(colName)){
        if (colName.equalsIgnoreCase("CcnCode")) {
        cell.setCellValue(row.getAttribute(colName).toString());
        System.out.println("colName "+colName+"row.getAttribute(colName).toString()"+row.getAttribute(colName).toString());
        }
        }
        //logic for cell formatting
       
        else if (colName.equalsIgnoreCase("CcnName")) {
        cell.setCellValue(row.getAttribute(colName).toString());
        }
       

 
        //make it double if you want and convert accordingly
        else if (colName.equalsIgnoreCase("CcnRegDate")){
        cell.setCellValue(row.getAttribute(colName).toString());
        }

 
        else if (colName.equalsIgnoreCase("CcnCancelDate")){

 
        if(null!=row.getAttribute(colName)){

 
        cell.setCellValue(row.getAttribute(colName).toString());

 
        }

 
        } else if (colName.equalsIgnoreCase("CcnUndertaking")){

 
        if(null!=row.getAttribute(colName)){
        cell.setCellValue(row.getAttribute(colName).toString());
        }
        }

 
        else if (colName.equalsIgnoreCase("CcnCode8")){

 
        if(null!=row.getAttribute(colName)){

 
        cell.setCellValue(row.getAttribute(colName).toString());

 
        }                                                                                                            }

 
        else
        cell.setCellValue(row.getAttribute(colName).toString());
        cellCounter++;
        }

 
        worksheet.createFreezePane(0, 1, 0, 1);
        }
        workbook.write(outputStream);
        outputStream.flush();
        }
       
       
        catch (Exception e) {
        e.printStackTrace();
        }         
        }

[code]
AM running out of memory

ShiftRows & Conserve Data?

$
0
0
Hi, I need a way to insert new cells and/or rows between pre-existing rows without deleting any of the rows.

I tried using:

Code:

        public static void addRow(File f, int amount, int currentRow)
                        throws Exception {
                FileInputStream file = new FileInputStream(f);
                XSSFWorkbook workbook = new XSSFWorkbook(file);
                XSSFSheet sheet = workbook.getSheetAt(0);
                sheet.shiftRows(currentRow, currentRow + amount, amount, true, true);
                file.close();
                FileOutputStream out = new FileOutputStream(f);
                workbook.write(out);
                out.close();
        }

But unfortunately it deletes some rows down the line to accommodate the shift. The deleted rows seem to be random they aren't actually directly below the shifted rows or above. They seem to happen inbetween shifted rows if I shift more than one row.


Thank you in advance for your help. :(nod):

Conditional Formatting

$
0
0
In previous version of POI, it is noted that ConditionalFormattingRule containing formulas containing cell references are not parsed properly.

I installed version 3.10 and it appears to behave the same way as before. Cell references are not updated for a range of cells.

Is there workaround or other method that should be used to apply ConditionalFormattingRule?

When using the code below, on row 3, the reference is still A2 instead of being recalculate.

Example:
SheetConditionalFormatting sheetCF = sheet.getSheetConditionalFormatting();

ConditionalFormattingRule rule = sheetCF.createConditionalFormattingRule( "AND($A2=\"\",OR($B2=\"PPA\",$B2=\"PAX\"))");

PatternFormatting ruleFmt= rule.createPatternFormatting();
ruleFmt.setFillBackgroundColor(IndexedColors.RED.i ndex);

CellRangeAddress[] ruleRange = {CellRangeAddress.valueOf("A2:A100")};

sheetCF.addConditionalFormatting(ruleRange, rule);

Return a range of cells with Apache POI Java API, Excel and Java

$
0
0
I have 3 named ranges on excel, say,

Name COUNT_FAM Refers To "COUNTA(Sheet1!$X$X)"
Name FAMILIES Refers To "INDIRECT(Sheet1!I2:I"&COUNT_FAM")"
Name FLEX_SOM Refers To "OFFSET(Sheet1!$Y$2, 0, 0, COUNT_FAM-1, 3)".
Now, I need a function that returns to me the range of cells (like A1:A4) or just display the cell(s) if I pass the workbook and the Refers To string as parameters. How could this be coded in Java using Apache POI Java API?

I tried to write a method that takes the file location and name of the range as inputs instead of workbook and refers to. Here is what I have coded:

public static void formulafn(String fileName, String rangeName) throws FileNotFoundException, IOException {

FileInputStream file = new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFName[] names = new XSSFName[workbook.getNumberOfNames()];
for (int i = 0; i < names.length; i++) {
names[i] = workbook.getNameAt(i);
}

for (int i = 0; i < names.length; i++) {
if (names[i].getNameName().matches(rangeName)) {
XSSFEvaluationWorkbook hssfew = XSSFEvaluationWorkbook.create(workbook);
Ptg[] ptg = FormulaParser.parse(names[i].getRefersToFormula(), hssfew, FormulaType.NAMEDRANGE, 0);
System.out.println(names[i].getNameName()+"\t"+names[i].getRefersToFormula());
for(int y=0;y<ptg.length;y++){
System.out.print(ptg[y]+"\t");
}
Ptg tempptg = ptg[ptg.length-1];
if(tempptg instanceof FuncVarPtg){
FuncVarPtg ref = (FuncVarPtg) tempptg;
if(ref.getName().equalsIgnoreCase("counta")){
}
}
}
}
}
I don't know how to proceed after this.

Thanks!
Viewing all 120 articles
Browse latest View live


Latest Images