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

Similar Messages

  • 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

  • Help with Appleworks-Spreadsheet - "Dragging down formula for entire column

    I have Appleworks 6 and am attempting to duplicate what I can do in Excel - Namely, entering a simple formula (=a1*.20) and dragging the lower righthand corner down to duplicate for the entire column. I know that Appleworks doesn't mimic many of Excel's features but am wondering what the Apple variation of this is?
    Thanks,
    Roberta

    You can "Fill Down" (or Fill Right) from the Calculate menu. Enter your formula, text, etc. it the first cell, click on that cell & drag the cursor until all of the cells you want to populate are highlighted, the choose your fill. Unless the original formula has absolute references, the filled formulas will be relative to the original cell. Say C1 is the first cell & the formula is =A1+B1, filling down from C1, the formula in C6, for example, will be =A6+B6.
    Peggy

  • Failed validation highlights entire column in tabular form

    Hi,
    I have a tabular form where one of the field is a date field. I need to ensure that that the date selected or entered falls in the correct range of another page item P6_WEEK_ENDING. Here is my code.
    DECLARE
         last_week_fri      DATE;
         this_week_fri     DATE;
         in_range NUMBER:=1;
         ret_bool BOOLEAN := TRUE;
    BEGIN
         -- Get current end of week ID
         this_week_fri:= CONVERTDATE2(:P6_WEEK_ENDING);
         SELECT CONVERTDATE2(this_week_fri-7) INTO last_week_fri FROM DUAL;
         FOR i in 1..apex_application.g_f03.count LOOP
              IF apex_application.g_f03(i) IS NOT NULL THEN
                   CASE
                        WHEN CONVERTDATE2(apex_application.g_f03(i)) >= CONVERTDATE2(last_week_fri) AND CONVERTDATE2(apex_application.g_f03(i)) <= CONVERTDATE2(this_week_fri) THEN
                             null;
                        ELSE
                             in_range:=0;                    
                   END CASE;
              END IF;
              if in_range != 1 THEN
                   ret_bool:= FALSE;
                   EXIT;
              END IF;          
         END LOOP;
         return ret_bool;
    END;Where
    convertdate2 takes date format and outputs date in dd-mm-yyyy format.
    apex_application.g_f03(i) is the date field.
    Now it all works well except when my validation fails, it highlights the entire column instead of highlighting the only the bad entries.
    I have my execution scope as : Created and Modified Rows, tried changing it with no luck.
    Many thank.
    Environment: APEX.4.1.1 using Sand theme

    Taepodong ,
    I assume this is a validation. When you first created the validation, you either selected a page item or tabular form. If you selected the latter, you then selected the tabular form to which the validation would apply. On the next screen, you were asked to "Identify the validation level:" I am guessing that, at that point, you selected "Tabular Form Row" rather than "Column" The former will highlight the entire row, while the latter will only highlight the column which was specified.
    -Joe

  • Can I have a product formula in an entire column that will multiply the previous two columns?

    Trying to enter a product formula for an entire column that will multiply the previous two columns without having to select each row of two cells and clicking on "product".  This is tedious.  Thanks.

    My own tip to apply fill down to a column :
    click the tab at top of the column to select the entire column
    press command then click the header cells to unselect them
    Trigger Table > Fill > Fill Down
    It's the kind of info which is available in Numbers User Guide.
    It's always good practice to Read The Free Manual.
    Yvan KOENIG (VALLAURIS, France) mercredi 21 septembre 2011 21:07:53
    iMac 21”5, i7, 2.8 GHz, 4 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.0
    My iDisk is : <http://public.me.com/koenigyvan>
    Please : Search for questions similar to your own before submitting them to the community

  • Installing formula for entire  Column

    Im putting together a wholesale business and want to format a column so that when I enter a price in column D column E automatically calculates and additional 15% for Freight. So As I proceed down each row with additional items when I enter the price of each item in Column D the landed cost of the good(with the additional 15%) automatically appears in column E... I know how to format each cell individually but want to format all the cells in the column at the same time.

    muleneck,
    You said you wanted to calculate a new price including freight when you entered a basic price. So suppose you are entering this basic price in B3. Then your new price in, say, C3 would be:
    =IF(B3="","",1.15*B3). This says, if there is no price value in B3, leave the cell (C3) blank. But if the price cell has a value, find the new price by adding 15% (.15) to that price or 1.15 times the original price. This lets you add rows not yet in use without seeing results of the calculation. But it's there when you enter a price.
    pw
    Message was edited by: pw1840

  • I can't figure out how to carry a formula down the entire column.

    I have done my best to figure this out, but I still can't. I know the solution is a simple one, but none the less, I can't seem to catch on.

    In Numbers, select the cell with the original formula and however many cells you want to use below it in the column, then select Insert > Fill > Fill Down.
    Alternatively, select only the cell with the original formula, then drag the tiny circle in the lower right corner of that cell down across the other cells.
    Message was edited by: markwmsn
    Added alternative method.

  • Why won't 'IF-Statement' Formula work for an entire column?

    I am trying to make an IF formula subtract a cells value from another cells value, creating a 'balance'.  The formula is working when selecting one cell for each part of the formula, but is not working when I try to use the formula for multiple cells (entire column).  The formula I am using for single cells is as follows:
    =IF(Monthly Timeline :: F2="Citi",Monthly Timeline :: D2+1000,1000)
    The formula works with way, when I select the pop-up menu in F2 to say "Citi" it will add the value of D2 to 1000 and give me a proper solution, but when I change it to the entire column as follows:
    =IF(Type="Citi",Amount+1000,1000)
    The formula for entire columns 'Type' and 'Amount' does not produce a proper solution, it will display 1000, no matter how many values in the 'Amount" column have "Citi" selected in the pop-up menu in the 'Type' column.
    I know there is a way to make this formula work but I can't seem to figure out what I am doing wrong  any help would be greatly appreciated.
    Thanks!

    the function if() does not apply to a column.  the functions sumif() and sumifs() do apply to columns.  You can get detailed information regarding these functions in the function browser.  To open the function browser select the menu item:
    "View > Show Function Browser"
    OR dowload the free function reference from Apple here:
    http://support.apple.com/manuals/#productivitysoftware
    The document is titled "iWork '09 Formulas and Functions User Guide"
    There is also a User Duide you may find helpful: "Numbers '09 - User Guide"

  • Large datasets...paste a formula into entire column

    I have a large data set....>40,000
    How do I past a formula to an entire column?
    e.g. Score a value using "if/then" logic to the entire dataset
    thanks
    Ryan

    You said "entire column" but maybe you meant "entire column except for header and/or footer rows"?
    If have header cells to avoid, do what Wayne said but after selecting the entire column, Command Click on the header cell(s) to deselect them. If you have footer rows, scroll to the bottom and deselect them too.

  • Diff between valid for consolidation and aggregation property in ODI column

    Hi John,
    I have a query regarding the columns when we revers the dimensions in ODI. In the columns tab of each dimension, there is valid for consolidation column. What does this column to when we select it. Coz any how i will be using the aggregation for plan type where i will be giving the consolidation operator. Could you please let me know the differences between them
    And also there is one more column Operation. What does this do

    Hi,
    You can ignore the "valid for consolidation column" as far as I am aware it is not used.
    Operation is for different types of load, these are
    Update (default)–Adds, updates, or moves the member being loaded.
    Delete Level 0–Deletes the member being loaded if it has no children.
    Delete Idescendants–Deletes the member being loaded and all of its descendants.
    Delete Descendants–Deletes the descendants of the member being loaded, but does
    not delete the member itself.
    Cheers
    John
    http://john-goodwin.blogspot.com/

  • How can I move columns in Numbers without distorting the formula in other cells?  In Excel I can cut and paste entire columns and the formula in other cells adjusts accordingly.  When I do it in Numbers, the formula messes up.  How can I do this?

    How can I move columns in Numbers without distorting the formula in other cells?  In Excel I can cut and paste entire columns and the formula in other cells adjusts accordingly.  When I do it in Numbers, the formula messes up.  How can I do this?
    For example: I have formulas in columns D and F that relate to columns C to CU
    If I want to move one column from one position to another (say S to T), the formula loses the colums that was moved, i.e. it doesn't recognize it has moved, rather sees it as deleted...  How can I do this without distorting the formula?

    Thanks for the feedback.
    If I often urge askers to look at the available resources, it's because  a large range of questions asked in the forums are already answered in these documents.
    As they are PDFs, they are easy to search in.
    CAUTION
    Download them while they are available.
    Given what is delivered with iBooks Author, I'm afraid that we will not get such easy to use documents.
    Searching infos in the  iBooks Author documentation available on line is awfully cumbersome and a lot of embedded links are wrongly flagged this way. In the Help files they aren't links but underlined strings.
    It seems that the tool used to generate the web pages was wrongly configured.
    Yvan KOENIG (VALLAURIS, France) dimanche 22 janvier 2012
    iMac 21”5, i7, 2.8 GHz, 12 Gbytes, 1 Tbytes, mac OS X 10.6.8 and 10.7.2
    My Box account  is : http://www.box.com/s/00qnssoyeq2xvc22ra4k
    My iDisk is : http://public.me.com/koenigyvan

  • Apply formula to entire column

    I am putting together a spreadsheet using Numbers 09.  I can apply a formula to an individual cell. I want to add the revenue in C2 + E2 to give me a sum in F2.  What I want to do is apply the formula to all of the cells in  Column F.    I know there is a way to apply a formula for every cell in Column F as i have done this before.  I can't remeber how I did it.  Any suggestions?

    Waughaw,
    There are two ways to do this:
    1. Enter the expression in F2. In your case the expression would be:
    =C+E
    Copy the F2 Cell. To do this reliably, you can click off F2, then click once on F2 to highlight the cell (not the content of the cell) and Command-C.
    Then Click on the Column Tab (the letter F in this case). This Selects the entire column. Command-Click on the Header cell to De-Select just that cell. Finally, Command-V. Your formula will now be inserted in every cell of Column F except the Header Cell.
    2. Enter the expression in F2.
    Again, the expression will be C+E
    Select the cell F2, as  above, and then examine the border of the cell.
    There will be a small open circle in the lower right corner of the cell. That's called the Fill Handle.
    Drag the Fill Handel to the bottom of the column.
    That's it.
    Jerry

  • How do I write a macro that would look for a string in an entire column

    how do I write a macro that would look for a string in an entire column. If the string is found, it will copy that entire row to a new sheet in that same file?
    I want to look in an entire column lets say "C" for different strings of numbers like 246, 88, 68, 82246 etc... and copy them to a new sheet
    Thanks

    Hello Larbec,
    Try this:
    Option Explicit
    Sub test()
        Dim myNumber As Integer
        Dim myNumbers() As Integer
        Dim i As Integer
        Dim c As Range
        Dim firstAddress As Variant
        myNumbers = Array(246, 88, 68, 82246)
        For i = 0 To UBound(myNumbers)
            myNumber = myNumbers(i)
            With ActiveSheet.Range("C:C")
                Set c = .Find(myNumber, LookIn:=xlValues)
                If Not c Is Nothing Then
                    firstAddress = c.Address
                    Do
        ' Copy c.value to OtherSheet here !!!!
                        Set c = .FindNext(c)
                    Loop While Not c Is Nothing And c.Address <> firstAddress
                End If
            End With
        Next i
    End Sub
    Best regards George

  • Settin singleton property false for child node but entire column populated

    hai all,
           I have set the singleton property of child node as false but still in my wdmodifyview when i load a value help with values from backend based on the user selection in 1st column of table the entire column gets populated.
    coding used by me:
    public static void wdDoModifyView(IPrivateSalesdet wdThis, IPrivateSalesdet.IContextNode wdContext, com.sap.tc.webdynpro.progmodel.api.IWDView view, boolean firstTime)
        //@@begin wdDoModifyView
       try
       String partfn=wdContext.currentTablepartnersElement().getPartnerfn();
         if(partfn.equals("ShiptoParty"))
    IWDAttributeInfo partattributeInfo=wdContext.nodeTablepartners().nodeTablepartnerssubnode().getNodeInfo().getAttribute(IPrivateSalesdet.ITablepartnerssubnodeElement.PARTNERS);
    ISimpleTypeModifiable part  = partattributeInfo.getModifiableSimpleType();
          //     Set field label and populate valueset
      part.setFieldLabel("key");
    IModifiableSimpleValueSet partvalueSet =  part.getSVServices().getModifiableSimpleValueSet();     
      for (int i = 0; i < wdThis.wdGetSalescustomctrllerController().wdGetContext().nodeLt_Kna1().size();i++)
    partvalueSet.put(wdThis.wdGetSalescustomctrllerController().wdGetContext().nodeLt_Kna1().getLt_Kna1ElementAt(i).getKunnr(),wdThis.wdGetSalescustomctrllerController().wdGetContext().nodeLt_Kna1().getLt_Kna1ElementAt(i).getName1());
    I need to populate only the table cell wch is next to the cell in wch user has made a selection  and not the entire column.plz help me in this issue.

    First, you should not place this code in wdDoModifyView().
    Second, I assume you want to have a value help only on a specific table cell, not for all cells in the same column, is that correct?
    This cannot be done by modification of the DDIC type because the type is used for all cells of a column. This has nothing to do with singleton vs. non-singleton.
    What exactly is your use case?
    Armin

  • Order of precedence for validation of a column in a table ?

    Can anybody tell me order of precedence for validation of a column in a table
    Which one will get executed first ?
    Integrity constraint or Database trigger.

    Why cant you test it..?
    SQL> create table test_1
      2  (c1 number references emp);
    Table created.
    SQL> create or replace trigger trig_1
      2  before insert on test_1
      3  for each row
      4  begin
      5  if :new.c1 < 1 then
      6   raise_application_error(-20000,'Invalid value');
      7  end if;
      8  end;
      9  /
    Trigger created.
    SQL> insert into test_1
      2  values(0);
    insert into test_1
    ERROR at line 1:
    ORA-20000: Invalid value
    ORA-06512: at "SCOTT.TRIG_1", line 3
    ORA-04088: error during execution of trigger 'SCOTT.TRIG_1'
    SQL> create or replace trigger trig_1
      2  after insert on test_1
      3  for each row
      4  begin
      5  if :new.c1 < 1 then
      6   raise_application_error(-20000,'Invalid value');
      7  end if;
      8  end;
      9  /
    Trigger created.
    SQL> insert into test_1
      2  values(0);
    insert into test_1
    ERROR at line 1:
    ORA-20000: Invalid value
    ORA-06512: at "SCOTT.TRIG_1", line 3
    ORA-04088: error during execution of trigger 'SCOTT.TRIG_1'
    SQL> drop trigger trig_1;
    Trigger dropped.
    SQL> insert into test_1
      2  values(0);
    insert into test_1
    ERROR at line 1:
    ORA-02291: integrity constraint (SCOTT.SYS_C005925) violated - parent key not
    found                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for