Apache POI Word support - workaround for a write bug

Hi all,
Just finished battling with the bugs in POI HWPF component. When searching forums, I found more questions than answers so I wanted to save others a significant effort until POI guys implement all the fixes.
Basically, the synopsis is, all the delete() methods are broken and replacing a string with a string of a different size corrupts the document. But insertAfter and insertBefore methods are mostly working.
I did not want to add a method to their class, because it will probably be overwritten. On the other hand, it is unknown when it will be fixed. Therefore, I had to go via reflection.
Here's the method, just attach it to your class and it's ready to use:
      * Replaces text in the paragraph by a specified new text.
      * @param r     A paragraph to replace.
      * @param newText     A new text.
      * @throws Exception     if anything goes wrong
     protected void setParagraphText(Paragraph r, String newText) throws Exception {
          int length = r.text().length() - 1;
          Class clRange = Range.class;
          Field fldText = clRange.getDeclaredField("_text");
          fldText.setAccessible(true);
          Field fldTextEnd = clRange.getDeclaredField("_textEnd");
          fldTextEnd.setAccessible(true);
          Field fldStart = clRange.getDeclaredField("_start");
          fldStart.setAccessible(true);
          List textPieces = (List)fldText.get(r);
          int _textEnd = fldTextEnd.getInt(r);
          TextPiece t = (TextPiece)textPieces.get(_textEnd - 1);
          StringBuffer sb = t.getStringBuffer();
          int offset = fldStart.getInt(r);
          int diff = newText.length() - length;
          if (diff <= 0) {
               // delete doesn't work properly yet, corrupting the documents.
               // Therefore a quick and ugly workaround is to pad the new text with spaces
               for (int i = 0; i < -diff; i++)
                    newText += " ";
               sb.replace(offset, offset + length, newText);
          } else {
               // when the new text is longer, the old one must be replaced
               // character by character, and the difference is added using
               // insertAfter method
               if (r.isInTable()) {
                    // more obstacles when working with tables though.
                    // Not only the regular insertAfter does not work,
                    // but also insertAfter called from a cell overruns cell delimiters.
                    // Needless to say, getTable(r) does not return the required table.
                    // Fortunately, there's a workaround
                    TableIterator ti = new TableIterator(range);
                    TableCell tc;
                    while (ti.hasNext()) {
                         Table tbl = ti.next();
                         for (int i = 0; i < tbl.numRows(); i++) {
                              TableRow tr = tbl.getRow(i);
                              for (int j = 0; j < tr.numCells(); j++) {
                                   tc = tr.getCell(j);
                                   if (tc.text().startsWith(sb.substring(offset, offset + length))) {
                                        sb.replace(offset, offset + length,
                                                  newText.substring(newText.length() - length));
                                        // only like this, otherwise cell delimiter will be run over
                                        tc.insertBefore(newText.substring(0, newText.length() - length));
                                        return;
                    sb.replace(offset, offset + length, newText.substring(0, length));
               } else {
                    sb.replace(offset, offset + length, newText.substring(0, length));
                    r.insertAfter(newText.substring(length));
     }

user8984775 wrote:
My requirement is I need to apply this formula for Entire column to achieve the need like
When user enters data in col2 (B) of greater than the number specified in col1 (A) and then show the ErrorBox.
I am able to get the formula working through code only for first cell as per below code... I want it to dynamically apply for the entire column. Well I'm certainly no expert on POI, but that looks like a very odd formula to me.
When you "pull" a formula down a column, Excel automatically changes the formula for each row, but because you've fixed both the column AND the row ($A$1), it'll be the same in all cases.
I don't know if POI allows that sort of "auto-generate" for formulas, but if so try something like $A1 instead; otherwise I suspect you'll need a different formula for each row.
Winston

Similar Messages

  • Apache POI- HSSFDataValidation Formula Validation for Entire column

    Hello,
    I have been looking HSSFDataValidation and was able to run the sample below.
    My requirement is I need to apply this formula for Entire column to achieve the need like
    When user enters data in col2 (B) of greater than the number specified in col1 (A) and then show the ErrorBox.
    I am able to get the formula working through code only for first cell as per below code... I want it to dynamically apply for the entire column.
    Please suggest...
       1. import java.io.File; 
       2. import java.io.FileOutputStream; 
       3. import java.util.ArrayList; 
       4. import org.apache.poi.hssf.usermodel.DVConstraint; 
       5. import org.apache.poi.hssf.usermodel.HSSFDataValidation; 
       6. import org.apache.poi.hssf.usermodel.HSSFSheet; 
       7. import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
       8. import org.apache.poi.hssf.util.CellRangeAddress; 
       9. import org.apache.poi.hssf.util.CellRangeAddressList; 
      10. import org.apache.poi.ss.usermodel.Cell; 
      11. import org.apache.poi.ss.usermodel.Row; 
      12.  
      13. public class TestThis{  
      14. public static void main1(String[] args) { 
      15.         // New Workbook.  
      16.         File outputFile = new File("C:/mamatha.xls"); 
      17.         try { 
      18.             
      19.             FileOutputStream fos = new FileOutputStream(outputFile); 
      20.             HSSFWorkbook workbook = new HSSFWorkbook(); 
      21.             HSSFSheet sheet = workbook.createSheet("Validation"); 
      22.             Row row = sheet.createRow(0); 
      23.             Cell cell = row.createCell(0); 
      24.             cell.setCellValue(5); 
      25.             cell = row.createCell(1); 
      26.             cell.setCellValue("good"); 
      27.             row = sheet.createRow(1); 
      28.             cell = row.createCell(0); 
      29.             cell.setCellValue(7); 
      30.             cell = row.createCell(1); 
      31.             cell.setCellValue("now"); 
      32.  
      33.             //String formula = "IF(LEN($B$1) > $A$1, FALSE, $B$1)"; 
      34.             String formula = "IF(LEN($B$1:$B10) > $A$1:$A10, FALSE, $B$1:$B10)"; 
      35.             CellRangeAddressList addressList = new CellRangeAddressList(); 
      36.             addressList.addCellRangeAddress(0, 1, 3, 1); 
      37.             DVConstraint constraing = DVConstraint.createFormulaListConstraint(formula); 
      38.  
      39.             HSSFDataValidation dataValidation = new HSSFDataValidation(addressList, constraing); 
      40.             dataValidation.setEmptyCellAllowed(true); 
      41.             dataValidation.setShowPromptBox(true); 
      42.             dataValidation.setSuppressDropDownArrow(false); 
      43.             dataValidation.createErrorBox("Invalid input !!", " Length of Col B > colA "); 
      44.             sheet.addValidationData(dataValidation); 
      45.             workbook.write(fos); 
      46.         } catch (Exception e) { 
      47.             System.out.println(e); 
      48.         } 
      49.     } 
      50. }  Thanks
    Mamatha
    Edited by: user8984775 on Mar 17, 2011 11:20 PM
    Edited by: user8984775 on Mar 17, 2011 11:22 PM

    user8984775 wrote:
    My requirement is I need to apply this formula for Entire column to achieve the need like
    When user enters data in col2 (B) of greater than the number specified in col1 (A) and then show the ErrorBox.
    I am able to get the formula working through code only for first cell as per below code... I want it to dynamically apply for the entire column. Well I'm certainly no expert on POI, but that looks like a very odd formula to me.
    When you "pull" a formula down a column, Excel automatically changes the formula for each row, but because you've fixed both the column AND the row ($A$1), it'll be the same in all cases.
    I don't know if POI allows that sort of "auto-generate" for formulas, but if so try something like $A1 instead; otherwise I suspect you'll need a different formula for each row.
    Winston

  • Workaround for H264 playback bug on Android?

    We have been doing extensive testing on H264 playback in both FLV and MP4 containers on Android AIR 3.2 / 3.3 (beta 3) for ICS. The process is documented here:
    https://bugbase.adobe.com/index.cfm?event=bug&id=3164920
    Summarized:
    ==========
    Android AIR 3.2 / 3.3 (beta 3) H264 playback (both in FLV and MP4 container) on Android 4 is severely broken.
    Video object (not StageVideo) with H264 content is:
    1) not playing videos consistently ("NetStream.Play.Stop" is triggered to early) so the movie stops before the end is reached. This also happens on Android 3. Note! The bug is not in AIR 3.1.
    2) not supporting filters (video frame is being scaled). Only Android 4 (ICS).
    3) not supporting seeking when video is paused (video frame is not being updated). Only Android 4 (ICS).
    Is there any known workarounds for these bugs?
    Best,
    Bjørn Rustberggard
    Co-founder
    WeVideo

    Hi,
    I just wanted to follow up.  It looks from your bug comments like the issues you experienced in AIR 3.2 have been resolved AIR 3.3.
    Are there any outstanding problems that you're seeing with regard to the issues you've described that we need to look into further for AIR 3.3? 
    Thanks!

  • Suggested workaround for list itemrenderer bug?

    Can someone point me in the right direction for a workaround for the problem described as Flex bug 28191:
    https://bugs.adobe.com/jira/browse/SDK-28191
    Steps to reproduce:
    1. Populate a Tree/List with data and provide a custom itemRenderer class factory.
    2. Change the class factory and dataProvider at the same time.
    3. List.createItemRenderer() will crash during since Factory is the key and it has been changed.
                    delete freeItemRenderersByFactory[factory][renderer];
    Actual Results:
    Crash because the renderer can not be found since it does not exist on that factory dictionary since the class factory was changed and the lookup is using the new factory.
    Expected Results:
    Not crash.
    Seems like a race condition, as sometimes during this process it skips that block of code but in other cases it falls into this block and fails.
    I need to change the data provider and item renderer of a tree control at runtime. Is there one or more methods I should run to prevent this? As the bug notes state, this is an intermittent problem. The error occurs here:
    if (factory == itemRenderer)
                if (freeItemRenderers && freeItemRenderers.length)
                    renderer = freeItemRenderers.pop();
                    delete freeItemRenderersByFactory[factory][renderer];

    Thanks. Actually, I have been updating (not setting or changing) the tree's dataprovider, and then changing the classFactory like this:
    processesXML = event.result as XML;
    nodeTreeData.source = processesXML.children();
    if (treeMultiSelect)
    nodeTree.itemRenderer=new ClassFactory(renderers.TreeItemRendererV1);
    nodeTree.allowMultipleSelection = true;
    nodeTree.setStyle("selectionColor", "0xFFFFFF");
    nodeTree.setStyle("disclosureOpenIcon", MinusIcon);
    nodeTree.setStyle("disclosureClosedIcon", PlusIcon);
    else
    nodeTree.itemRenderer=new ClassFactory(mx.controls.treeClasses.TreeItemRenderer);
    nodeTree.allowMultipleSelection = false;
    nodeTree.setStyle("selectionColor", "0x7FCEFF");
    nodeTree.setStyle("disclosureOpenIcon", OpenArrowIcon);
    nodeTree.setStyle("disclosureClosedIcon", ClosedArrowIcon);
    I had tried using validateNow after changing the ClassFactory before but did get the error again. I will try it again but update the data provider after. Since it's an intermittent error I'm finding it hard to know if a fix is really working.

  • WARNING: workaround for critical clustering bug in OC4J

    I found a workaround for the HTTP clustering bug described in my previous posting of August 16, 2001 "Urgent: serious HTTP clustering bug in OC4J?" (http://technet.oracle.com:89/ubb/Forum99/HTML/000261.html)
    The workaround:
    When adding the <cluster config/> tag in orion-web.xml specify and ID (numeric) with no more than 9 figures. The autogenerated ID is longer (14 figures on my test system)
    and will cause the error.
    Luciano
    null

    burricall wrote:
    ..Did you find a solution?See [this post|http://forums.sun.com/thread.jspa?threadID=5426321&messageID=11001580#11001580].

  • Has anyone come up with new workarounds for Logic routing bugs?

    There have been many threads regarding what seem to be a set of similar bugs. These inlude an audio intrument not sounding after a while, or a channel of automation not being read; and the problem is easily fixed by closing and re-opening the song. That would be a fine workaround except that some songs take a long time to load. I used to have these problems occasionally, but recently they have become so common as to be almost constant. That's bad news, but it also is potentially good news since it means that something in my system has an influence on these bugs. I haven't found a thread in which anyone isolated a factor that helps or hurts, but it's hard to imagine all the keywords for this set of problems, so maybe I missed an idea.
    Also a new similar bug has started appearing in my system. When I add a bus send, once in a while either some or all audio channels will go silent, even though the graphic indicators indicate that they should be heard. The silent channels might or might not include the one with the new bus send. Remove the bus send and the sound comes back.
    It seems as though changes in routing have binding problems.
    Thanks for any ideas!

    Absolutely no ideas on workarounds. I have the exact same issues.
    Most of the time restarting the computer and session will cure them, but there have been projects where no matter what I do, the faders will not follow the automation data and EXS24 instruments cut out at the same exact time in the arrangement. This occurs even with as few as 6 EXS24 instruments open when on some projects I have up to about 85 open and 30 streaming at the same before I get a CoreAudio error.
    Terrible...terrible.
    Any word on whether or not 7.2 addresses this issues?

  • Workaround for ]] XML export bug with schema?

    Hi,
    It is a known issue that the ]]> sequence will not export properly to XML. If you are using a DTD, there is an entity-based workaround that is described here:
    http://forums.adobe.com/message/3774389
    The question... is there a workaround when using schema? I'm unable to figure it out.
    Thanks,
    Russ

    Hi Lynne,
    Thanks again for the thoughts. And by the way, I sympathize with your implicit complaint about how these forums work with respect to revised messages. I am accustomed to hitting Ctrl+S all the time, probably from my FM experience   Unfortunately, if you accidentally do it in the forum webpage, it submits the message. The system really needs to send revisions when they occur, because some people might just read the original email and think that's it.
    Anyway, I'm intrigued by some things you said. #1 is possible but not preferable, as schema was specifically chosen for the ability to validate attribute values. My level of attribute-based conditionalization is fairly heavy and the schema makes sure that an invalid value cannot be entered. I seem to remember back in the outset that a DTD couldn't do the level of validation I like, but I don't remember the exact reasoning. Note that I frequently assign lots of values to an attribute, tokenized with whitespace as customary.
    #3 is what I'm doing now, except with the fancy coverup tricks with spacing and back-end XSLT. I like your ideas.
    #4 is actually pure genious and it is the route I think I will go. Something you didn't know yet is that I have a script that automatically formats an XML instance like an XML editor does, incidentally by wrapping <ph> elements and setting color-formatting attributes. Thanks to ExtendScript, I was able to use regular expressions to parse out all the individual components and then create a "map" for the subsequent wrapping/formatting activities. It is quite lovely and gives me the best looking XML instances in town, with a click. Bragging aside, it would be elementary to modify that script slightly to insert another <ph> element as you suggest. Elegant and simple, but I would have never thought of that myself.
    Many thanks again,
    Russ

  • Workaround for JColorChooser setPreviewPanel bug?

    In 1.5:
    JColorChooser's setPreviewPanel(null) doesn't work.
    JColorChooser's setPreviewPanel(JPanel) removes the default preview panel but the new panel doesn't show up.
    This bug was supposed to be resolved for 1.4.2, but according to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6199676, it is still around. (there are many other related bug entries).
    Any workaround, please?

    Use the following code before you set the preview panel. For more info look at Bug ID 5029286
    previewPanel.setSize(previewPanel.getPreferredSize());
    previewPanel.setBorder(BorderFactory.createEmptyBorder(0,0,1,0));

  • Error in importing org.apache.poi

    hi.....i am getting only one error as "package org.apache.poi.hssf.usermodel does not exist" when i write the code as
    import java.io.*;
    import jxl.*;
    import java.util.*;
    import jxl.Workbook;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import jxl.write.DateFormat;
    import jxl.write.Number;
    import jxl.write.*;
    import java.text.SimpleDateFormat; "
    and also i added the jxl.jar file into my class path.......
    Can anybody plz tell me how can i eliminate that error.............Thanks in advance.
    Edited by: sumanthchowdary on Jun 2, 2008 11:34 PM

    What is there inside your jxl.jar.
    Apache POI library name is poi-3.0.2-FINAL-20080204.jar in the last release available on [http://www.apache.org/dyn/closer.cgi/poi/]. Check your classpath, IMHO it doesn't contain any POI class.
    Edited by: jswim on 3 juin 2008 09:39

  • How to Edit Word Document in Oracle ADF Application - Apache POI

    Hi All
    I was wondering if there is a way to edit and save word documents in Oracle ADF without loosing the Formatting.
    I was able to edit and save the word document however the Formatting was lost.
    Please let me know if there are any pointers or open source Java APIs that we can use to achieve this.

    Refer the Text Formatting section
    Apache POI - HWPF - Java API to Handle Microsoft Word Files
    HWPF Reads in a Word document with minimum formatting (no lists, tables, footnotes, endnotes, headers, footers)
    Apache POI - HWPF - Java API to Handle Microsoft Word Files
    The _cbt field in class HWPFDocumentCore contains formatting information.
    HWPFDocumentCore (POI API Documentation)
    For more advanced text extraction needs, including Rich Text extraction (such as formatting and styling), along with XML and HTML output, Apache POI works closely with Apache Tika to deliver POI-powered Tika Parsers for all the project supported file formats.
    Apache POI - Text Extraction
    Use Apache Tikka for formatting.
    Apache Tika - Supported Document Formats

  • Workarounds for lack of sub-folder support

    I'm trying to find a workaround for the lack of sub-folder support for photos. For example, are there any apps that synchronise my photos with the original folder structure from my PC? I've spent quite a lot of time searching, but can't find the right solution.

    Hi all. Hope this helps...
    There is NO sub-folder (two or more folder levels) support in OS3x and OS4x until today. Hope this will change in near future, however that also means foregoing smoothness operation of the iDevice due to how the internal memory works inside (so far, thousands of photos can be viewed without a lag because how fast the iDevice can find the memory location of each file inside its big memory, and creating sub-folders will take great amount of time for the processor to find, put-together, and present the many photos to screen).
    There are other applications that support photos with sub-folders (folders inside folders inside folders inside folders inside folders and so on), however these are not specialized photo viewing app and will not show picture thumbnails but file listing instead:
    - GoodReader
    - OPlayer
    Two good photo and video viewing apps with privacy security; Photo Safe and Video Safe, are also available, which supports high-definition without reducing photo quality as in original iDevice, BUT does not support sub-folders (only one level folders/albums).
    I was hoping iOS4 had the Sub-folders feature for its iPhoto... doesn't have to be three-folder levels, but just additional one level sub-folders would be great.
    Cheers!

  • Is there a workaround for websites that use "frames" when Safari does not support?

    Is there a workaround for a website that requires "frames" when Safari (5.0.6) does not support it?

    Has anyone found a work-around for this that works?
    No. Any attempt to use an unsupported network device with Time Machine will probably result in data loss, even if it seems to be working at first. If you take data protection seriously, you won't try.
    Is it possible to get Time Machine to use SMB to make the backups?
    No.

  • Can Robohelp for word support .PNG images

    Hii,
    Can anyone pls tell me whether Robohelp for Word supports
    images in .PNG format ?? (I am working on a Winhelp 2000 project) I
    am able to get good results for smaller word documents without
    converting the images into Help images, but the larger documents
    are not letting the help file to be generated. The generation
    process stops at processing the .rtf file. I don't want to convert
    my images, which consist of .bmp and .png files, into Help images
    because the output is very ugly.

    Thanks, that helped get rid of the problem. I had around 700
    images (ranging from small menu icons to full screen windows) in my
    Word document, and was trying to import the same into RH7. I
    divided the document into smaller documents because of the said
    problem. Now, one of these documents was again creating problem. I
    followed what you suggested regarding the images for that specific
    part only, and the problem has gone. Now my concern is, will those
    parts, where I have not inserted the images using the RH7 menu,
    create problem later on. For now, they are working perfectly, and
    the images are getting displayed properly. I have not converted any
    images into help images. But, the Insert Image dialog box did not
    support PNG files, hence I had to save the images as BMP (24 bit)
    first. What problems can I face because of simply importing the
    documents along with the images. Removing all the images, saving
    them, and inserting them again using the RH7 menu is going to take
    a hell lot of time.

  • I can not pay purchase what to do? writes address in support айтюнс for completion of this transaction

    I can not pay purchase what to do? writes address in support айтюнс for completion of this transaction

    Please post in your native language... this makes no logical sense.

  • Hello. help! My bonjour is missing for my itunes. I tried reinstalling and I get this message: "Support personnel could not write value manageLLRouting to key \SYSTEM\CurrentControlSet\ServicesBonjourService\parameters

    Hello, my Bonjour was missing from my computer for Itunes; I cannot find it in my programs so it seems it has been accidentally deleted. I tried re-installing and got this message: "Support personnel could not write value ManageLLRouting to key \SYSTEM\CurrentControlSet\Services\BonjourService\Parameters".  Someone please help as I am trying to get my itunes reinstalled and recognized by my phone. I use a Windows 7 software.
    Any assistance is truly appreciated.
    Thanks!

    That particular message might be triggered by Trend Antivirus. If so disabling the real time scanner while updating iTunes and other components should work.
    See also Troubleshooting issues with iTunes for Windows updates.
    tt2

Maybe you are looking for

  • How to find all the instances for specific recurring report

    How can I use UQery Builder to find out all the instance related to specific Recurring job. I have tried using following query to get the result with poor performance. select SI_ID, IS_SCHEDUILE_STATUS from ci_infoobjects where SI_NEW_JOB_ID = 260448

  • How to wipe all Windows 7 (Bootcamp) files, without removing the operating system?

    I have accumulated a lot of junk while using Windows 7 for a while, and I'd like a fresh start. Normally I would just delete the partition and reinstall. However, the only Windows licenses I have are a Windows XP license, and a Windows 7 UPGRADE Lice

  • The Sims 2, SimCity 4?

    Hello. I have just recently bought a 2.0 GHz C2D Macbook with 2GB of RAM. and i should recieve it by fedex tomorrow. i don't play computer games all that much but there are two that i absolutly love: The Sims 2 and SimCity 4 is the macbook capable of

  • *****output File format

    Hi all, Instead of Time stamp in the out put file ,we require the out put file format as xyz_a.txt,xyz_b.txt....... eg:file name sample.txt out put required is sample_a,sample_b,sample_c...... is it possible in Xi? Thanks, Srinivasa

  • How to enable the RSVP protocol in TE?

    ip rsvp bandwidth xxx? or something else? how to maintain the relationship?