How do i parse a csv into my inDesign script?

hi there, having real trouble with this:
// target the latest version of InDesign
#target "InDesign-10"
// This will parse a delimited string into an array of
// arrays. The default delimiter is the comma, but this
// can be overriden in the second argument.
// http://www.bennadel.com/blog/1504-ask-ben-parsing-csv-strings-with-javascript-exec-regular -expression-command.htm
function CSVToArray( strData, strDelimiter ){
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");
    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp(
            // Delimiters.
            "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
                // Quoted fields.
                "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
                // Standard fields.
                "([^\"\\" + strDelimiter + "\\r\\n]*))"
        "gi"
    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];
    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;
    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec( strData )){
        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[ 1 ];
        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (
            strMatchedDelimiter.length &&
                (strMatchedDelimiter != strDelimiter)
            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push( [] );
        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[ 2 ]){
            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[ 2 ].replace(
                new RegExp( "\"\"", "g" ),
        } else {
            // We found a non-quoted value.
            var strMatchedValue = arrMatches[ 3 ];
        // Now that we have our value string, let's add
        // it to the data array.
        arrData[ arrData.length - 1 ].push( strMatchedValue );
    // Return the parsed data.
    return( arrData );
// read source file
var csv = CSVToArray(File("../data/source.csv"), ",");
// create new document using specified presets
var myDocument              = app.documents.add();
var myTextFrame             = myDocument.pages.item(0).textFrames.add();
myTextFrame.geometricBounds =  ["6p", "6p", "24p", "24p"];
myTextFrame.contents        = "// this is where i want to pull a value from a specific cell within the csv.  I will have multiple TextFrames in the final script but want to see proof of concept before complicating further"

I haven't tested your code, you try the below code it may help you to parse the csv content:
// create new document using specified presets
var myDocument = app.documents.add();
var myTextFrame = myDocument.pages.item(0).textFrames.add();
myTextFrame.geometricBounds =  ["6p", "6p", "24p", "24p"];
var csvFile = File("../data/source.csv");//mention you csv path here
var Read1 = csvFile.open("r",undefined,undefined);
while(csvFile.eof == false)
    var Read2 = csvFile.readln();
    var LineArr = Read2.split(",");
    // LineArr[0] represent first column
    // LineArr[1] represent second column
    // LineArr[2] represent third column etc.
    myTextFrame.contents = myTextFrame.contents + "\r" + LineArr[0] + "\t" + LineArr[1];
    // if you want to validate any content try if statement like below:
        if(LineArr[0] == "CSV_CONTENT")
        myTextFrame.contents = LineArr[0]
Vandy

Similar Messages

  • How do I get a Euro into my InDesign document?

    I need to know how to insert a euro symbol into my Indesign document.
    I have looked at other posts and the suggestion of holding down the Alt key with 0128 doesn't work for me.
    Does anyone have any other suggestions please?
    I am based in England.
    Thanks

    Hey, I'm from Ireland and the Euro symbol is a pita.
    The keyboard comes fitted with an Alt Gr + 4 (the right alt key and the number 4 on the top row) but that does not translate well across RIPs and often come out as question marks or blank squares.
    Please use the Euro Font that is available for free http://www.adobe.com/type/eurofont.html
    Usually I will use a symbol I don't usually use in the document (being in Ireland I don't need the £ symbol at all), so I use that symbol but in the Euro Font, available in 3 different flavours with different weights.
    So pick a symbol you won't use and then apply the Euro font.
    I have a nested style for Euro symbols that applies it as a character style. And with CS4 it should be possible to use a GREP STYLE to apply the Euro font to anywhere you need the Euro symbol to show up.
    It's really the best option as it's a font and it's a character of a font and it won't drop out of the RIP.
    (Suggestions for alt characters to use could be ¬ or $ or ~ or #, for example. That way if you need to find $ or £ you still can without finding all the Euro Symbols too)

  • How to import multiple XML files into one inDesign document without copy/paste ?

    I use InDesign CS6, and I have several XML files with the same structure. Only the data are different.
    I created  an Indesign layout with some tagged placeholder frames on merge mode, for automated layout.
    Today for each XML file I have to create a new InDesign document to import the XML. Everything works fine. Then in order to have all Indesign layouts one after the other into a single Indesign layout, I have to use the copy/paste function.
    I mean for example, copy the contents of all documents to the first one. Or add pages of other documents to the first one, then delete spaces between each page.
    So my question is the following:
    How to repeat this process without copy/paste function, knowing that the
    number of XML files could be unknown.
    Thank you very much for your answer.

    Yes, effectively I would like to catalogue the files into one collection so i can save as one PDF and Print as one.:)
    I know I could save each AI as a pdf them then merge the pdf's together in acrobat, but I have nearly 100 files so would feel more comfortable seeing them all together before print / saving.
    My concern is that if I insert them in Ai, will the file resolution reduce? and will the ai still be editable and would it update the indesign file?
    Thanks for the quick reply

  • How to convert a large document into a InDesign Book w/Chapters?

    Hello!
    I just started a position with a company that has a number of catalogs full of the widgets they sell. Previously the catalog work was outsourced to a company that uses Quark, and the first thing I did when I started was to convert them to InDesign using a 3rd party plugin.
    The one I'm working on now is 400+ pages, including a TOC and 2 indexes (words / item nos.), and is currently 4 VERY large files that take 5-10 minutes each to open.
    What I'd like to do is split the entire catalog along logical lines into a bunch of 10-50 page documents, then stitch them all back together as Chapters in a Book file. The plan is to have the smaller documents be usable either as stand-alone brochures or as pieces of the big catalog. Once I can get it all organized the way I want, I'll be redoing the TOC and indexes as well.
    So, to boil it down to a few questions:
    1. How do I split a large document into smaller pieces?
    2. I have a basic understanding of creating a Book file, but are there any pitfalls I should watch out for when stitching the bits back together?
    3. Is it possible to have page numbering automated so that if I open a chapter on its own the pages will be, say, 1-20; but if I open it in the context of the book file the pages will be, say, 84-104?
    4. Are the page numbering, TOC, and indexing tools flexible enough to where if I modify a section such that it adds or removes pages in that section, the entire book file will restructure to accommodate?
    A thousand thanks in advance to all who read this, and to any who respond!

    S_Atwood wrote:
    Hello!
    I just started a position with a company that has a number of catalogs full of the widgets they sell. Previously the catalog work was outsourced to a company that uses Quark, and the first thing I did when I started was to convert them to InDesign using a 3rd party plugin.
    The one I'm working on now is 400+ pages, including a TOC and 2 indexes (words / item nos.), and is currently 4 VERY large files that take 5-10 minutes each to open.
    What I'd like to do is split the entire catalog along logical lines into a bunch of 10-50 page documents, then stitch them all back together as Chapters in a Book file. The plan is to have the smaller documents be usable either as stand-alone brochures or as pieces of the big catalog. Once I can get it all organized the way I want, I'll be redoing the TOC and indexes as well.
    So, to boil it down to a few questions:
    1. How do I split a large document into smaller pieces?
    Saving x-number of copies as new names, then chop off the unwanted parts is pretty efficient.
    2. I have a basic understanding of creating a Book file, but are there any pitfalls I should watch out for when stitching the bits back together?
    Nothing specific, other than learning the ins and outs of working with book files. For example, if you change a style in one file, you'd want to use the Synchronize feature to propagate the change to the other files, but you'd also need to remember if any change in one file shouldn't be propagated to others, and deselect it in the Synchronize dialog box.
    It's a good idea to open all and save all book files before doing any book-wide operation; even better to save the whole directory for safety. Working on open  files gives you some undo powers that working with closed files doesn't.
    3. Is it possible to have page numbering automated so that if I open a chapter on its own the pages will be, say, 1-20; but if I open it in the context of the book file the pages will be, say, 84-104?
    The individual files need to be checked and perhaps updated or have their numbering restarted when they're removed from the book file's control. It depends on how you've set up the numbering.
    4. Are the page numbering, TOC, and indexing tools flexible enough to where if I modify a section such that it adds or removes pages in that section, the entire book file will restructure to accommodate?
    A thousand thanks in advance to all who read this, and to any who respond!
    Both TOC and Index have check boxes to include all files in the current book. You need to update the TOC, and generate the index again with Replace Existing Index checked, after making changes.
    HTH
    Regards,
    Peter
    Peter Gold
    KnowHow ProServices

  • How do I get additional parameters into a Linux Script / PowerShell Discovery?

    Hi all,
    I'm trying to do a Linux Shell / PowerShell discovery as described in
    http://operatingquadrant.com/2013/07/30/unixlinux-mp-authoring-discovering-and-monitoring-failover-clusters/ but for the
    complex logic I need the GUID of the target object and the GUID of the discovery itself ($MPElement$ and $Target/Id$) as additional arguments to either of the scripts.
    I tried to insert them into the "ScriptArguments" tag - but they don't show up in either of the scripts.
    I tried to edit the code in VSAE, but it complains: "Could not find schema information for the element 'Scheduler'."
    I added the (SCSM) "Management Pack Schema Version 1.1 XSD" as described in the blog
    VSAE - Could not find schema information, but this also does not help.
    Any ideas?
    Thanks, Holger
    Holger alias "Marvin", the InternetSmurf, Munich, Germany // Where can I edit / remove this signature line? Please do not say "in your profile" - I searched all the profiles I found ...

    Hi Bob or Vladimir,
    here comes the code - I shortened it, I hope, everything necessary is contained:
    <TypeDefinitions>
    <ModuleTypes>
    <DataSourceModuleType ID="MyMP.Linux.XYZ.ServerDiscoveryDataSource" Accessibility="Internal" Batching="false">
    <Configuration>
    <IncludeSchemaTypes>
    <SchemaType>System!System.Discovery.MapperSchema</SchemaType>
    <SchemaType>System!System.ExpressionEvaluatorSchema</SchemaType>
    </IncludeSchemaTypes>
    <xsd:element name="Interval" type="xsd:integer" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="TargetSystem" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="ShellCommand" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="ScriptArguments" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="Timeout" type="xsd:integer" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="UserName" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="Password" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="PSScriptName" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="PSScriptBody" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="FilterExpression" type="ExpressionType" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="ClassId" type="xsd:string" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    <xsd:element name="InstanceSettings" type="SettingsType" minOccurs="1" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
    </Configuration>
    <OverrideableParameters>
    <OverrideableParameter ID="Interval" Selector="$Config/Interval$" ParameterType="int" />
    <OverrideableParameter ID="Timeout" Selector="$Config/Timeout$" ParameterType="int" />
    </OverrideableParameters>
    <ModuleImplementation Isolation="Any">
    <Composite>
    <MemberModules>
    <DataSource ID="Scheduler" TypeID="System!System.Discovery.Scheduler">
    <Scheduler>
    <SimpleReccuringSchedule>
    <Interval>$Config/Interval$</Interval>
    <SyncTime />
    </SimpleReccuringSchedule>
    <ExcludeDates />
    </Scheduler>
    </DataSource>
    <ProbeAction ID="InvokeProbe" TypeID="Unix.Authoring.ShellCommand.PropertyBag.ProbeAction">
    <TargetSystem>$Config/TargetSystem$</TargetSystem>
    <ShellCommand>$Config/ShellCommand$</ShellCommand>
    <ScriptArguments>$Config/ScriptArguments$</ScriptArguments>
    <Timeout>$Config/Timeout$</Timeout>
    <UserName>$Config/UserName$</UserName>
    <Password>$Config/Password$</Password>
    <PSScriptName>$Config/PSScriptName$</PSScriptName>
    <PSScriptBody>$Config/PSScriptBody$</PSScriptBody>
    </ProbeAction>
    <ConditionDetection ID="Filter" TypeID="System!System.ExpressionFilter">
    <Expression>$Config/FilterExpression$</Expression>
    </ConditionDetection>
    <ConditionDetection ID="Mapper" TypeID="System!System.Discovery.ClassSnapshotDataMapper">
    <ClassId>$Config/ClassId$</ClassId>
    <InstanceSettings>$Config/InstanceSettings$</InstanceSettings>
    </ConditionDetection>
    </MemberModules>
    <Composition>
    <Node ID="Mapper">
    <Node ID="Filter">
    <Node ID="InvokeProbe">
    <Node ID="Scheduler" />
    </Node>
    </Node>
    </Node>
    </Composition>
    </Composite>
    </ModuleImplementation>
    <OutputType>System!System.Discovery.Data</OutputType>
    </DataSourceModuleType>
    </ModuleTypes>
    </TypeDefinitions>
    <!-- ********** Monitoring ********** -->
    <Monitoring>
    <Discoveries>
    <!-- ***** XYZ Linux Server Discovery ***** -->
    <Discovery ID="MyMP.Linux.XYZ.ServerDiscoveryRule" Enabled="true" Target="Unix!Microsoft.Unix.Computer" ConfirmDelivery="false" Remotable="true" Priority="Normal">
    <Category>Discovery</Category>
    <DiscoveryTypes>
    <DiscoveryClass TypeID="MyMP.Linux.XYZ.Server">
    <Property TypeID="MyMP.Linux.Server" PropertyID="NetworkName" />
    <Property TypeID="MyMP.Linux.Server" PropertyID="Manufacturer" />
    <Property TypeID="MyMP.Linux.Server" PropertyID="Model" />
    </DiscoveryClass>
    </DiscoveryTypes>
    <DataSource ID="DS" TypeID="MyMP.Linux.XYZ.ServerDiscoveryDataSource">
    <Interval>600</Interval>
    <TargetSystem>$Target/Property[Type="Unix!Microsoft.Unix.Computer"]/NetworkName$</TargetSystem>
    <ShellCommand>
    <![CDATA[
    logfile="/tmp/scom.ServerDiscovery.log"
    echo "--------------------------------------" >> $logfile
    echo `date` >> $logfile
    echo Arguments: $* >> $logfile
    echo Arguments: .$1. .$2. .$3. .$4. .$5. >> $logfile
    export returnstring=""
    export systemmanufacturer=`dmidecode -s system-manufacturer | sed -e 's/^ *//' -e 's/ *$//'`
    echo "systemmanufacturer=$systemmanufacturer" >> $logfile
    returnstring="$returnstring#systemmanufacturer=$systemmanufacturer"
    export systemproductname=`dmidecode -s system-product-name | sed -e 's/^ *//' -e 's/ *$//'`
    echo "systemproductname=$systemproductname" >> $logfile
    returnstring="$returnstring#systemproductname=$systemproductname"
    echo "Done." >> $logfile
    echo "--------------------------------------" >> $logfile
    echo "$returnstring" >> $logfile
    echo "======================================" >> $logfile
    echo "$returnstring"
    #echo "ServerDiscovery=Done"
    ]]></ShellCommand>
    <ScriptArguments>$MPElement$ $Target/Id$ $Target/Property[Type="Unix!Microsoft.Unix.Computer"]/NetworkName$ $MPElement$ $Target/Id$</ScriptArguments>
    <Timeout>300</Timeout>
    <UserName>$RunAs[Name="Unix!Microsoft.Unix.PrivilegedAccount"]/UserName$</UserName>
    <Password>$RunAs[Name="Unix!Microsoft.Unix.PrivilegedAccount"]/Password$</Password>
    <PSScriptName>ServerDiscovery.ps1</PSScriptName>
    <PSScriptBody>
    <![CDATA[
    # Copyright (C) MyCompany 2014
    # ServerDiscovery.ps1
    # Summary:
    # Discover XYZ Linux Server.
    Param (
    [string]$StdOut,
    [string]$StdErr,
    [string]$ReturnCode,
    [string]$param4,
    [string]$param5
    $LogFile = "C:\scom\ServerDiscovery.log"
    $SplitChar = "#"
    function Main
    Param (
    [string]$StdOut,
    [string]$StdErr,
    [string]$ReturnCode,
    [string]$param4,
    [string]$param5
    DebugOut "-------------------------------------------------"
    DebugOut "Starting ServerDiscovery.ps1"
    DebugOut "$(Get-Date -Format F)"
    DebugOut "1 StdOut: $StdOut"
    DebugOut "2 StdErr: $StdErr"
    DebugOut "3 ReturnCode: $ReturnCode"
    DebugOut "4 param4: $param4"
    DebugOut "5 param5: $param5"
    if ($ReturnCode -eq "0")
    $serverProperties = $StdOut.split($SplitChar)
    foreach ($obj in $serverProperties)
    if ($obj -ne $null)
    $property = $obj.split("=")[0]
    $value = $obj.split("=")[1]
    switch ($property)
    "sourceid" { $SourceId = $value }
    "managedentityid" { $ManagedEntityId = $value }
    "hostname" { $PrincipalName = $value
    $TargetComputer = $value }
    "systemmanufacturer" { $Manufacturer = $value }
    "systemproductname" { $ModelName = $value }
    default { DebugOut "unknown Property/Value-Pair: $obj" }
    DebugOut "PrincipalName: [$PrincipalName]"
    DebugOut "TargetComputer: [$TargetComputer]"
    DebugOut "Manufacturer: [$Manufacturer]"
    DebugOut "ModelName: [$ModelName]"
    $oAPI = New-Object -ComObject "MOM.ScriptAPI"
    $oDiscoveryData = $oAPI.CreateDiscoveryData($SourceType, "{$SourceId}", "{$ManagedEntityId}")
    $oInst = $oDiscoveryData.CreateClassInstance("$MPElement[Name='MyMP.Linux.XYZ.XYZServer']$")
    $oInst.AddProperty("$MPElement[Name='Unix!Microsoft.Unix.Computer']/PrincipalName$", $PrincipalName)
    $oInst.AddProperty("$MPElement[Name='System!System.Entity']/DisplayName$", $TargetComputer)
    $oInst.AddProperty("$MPElement[Name='MyMP.Linux.Server']/NetworkName$", $TargetComputer)
    $oInst.AddProperty("$MPElement[Name='MyMP.Linux.Server']/Model$", $ModelName)
    $oInst.AddProperty("$MPElement[Name='MyMP.Linux.Server']/Manufacturer$", $Manufacturer)
    #*** Send the data to OpsMgr
    DebugOut "***** Return oDiscoveryData to OM; Normal exit *****"
    $oAPI.Return($oDiscoveryData) # Submit the data
    DebugOut ""
    DebugOut "***** Normal end of script. *****"
    Exit 0
    else
    DebugOut "No SourceId, no DiscoveryData ..."
    DebugOut "***** Bad ReturnCode $ReturnCode. End of script. *****"
    Exit $ReturnCode
    } # End of Main
    function DebugOut([string]$Text, [int]$dbg)
    Write-Host $Text
    echo $Text >> $LogFile
    Main $StdOut $StdErr $ReturnCode $param4 $param5
    ]]></PSScriptBody>
    <FilterExpression />
    <ClassId>$MPElement[Name="MyMP.Linux.Server"]$</ClassId>
    <InstanceSettings>
    <Settings>
    <Setting>
    <Name>$MPElement[Name='Unix!Microsoft.Unix.Computer']/PrincipalName$</Name>
    <Value>$Target/Property[Type="Unix!Microsoft.Unix.Computer"]/PrincipalName$</Value>
    </Setting>
    <Setting>
    <Name>$MPElement[Name='MyMP.Linux.Server']/NetworkName$</Name>
    <Value>$Data/Property[@Name='NetworkName']$</Value>
    </Setting>
    <Setting>
    <Name>$MPElement[Name='System!System.Entity']/DisplayName$</Name>
    <Value>NetworkName: $Data/Property[@Name='NetworkName']$</Value>
    </Setting>
    </Settings>
    </InstanceSettings>
    </DataSource>
    </Discovery>
    </Discoveries>
    </Monitoring>
    Thanks, Holger.
    Holger alias InternetSmurf, Munich, Germany

  • Need help with getting images to look smooth (without the bitmap squares) around the edges. When I transfer the image from pictures, it sets itself into the InDesign layout, but with square edges. I need to find out how to get it to look smooth?

    Need to find out how to get my images transferred into an InDesign layout without the rough edges, as with a bit map image, but to appear with smooth edges in the layout. I can notice it more when I enlarge the file (pic). How can I get it to appear smooth in the finished layout. Another thing too that I noticed; it seems to have effected the other photos in the layout. They seem to be
    pixelated too after I import the illustration (hand drawn artwork...)? Any assistance with this issue will be greatly appreciated. Thanks in advance.

    No Clipboard, no copy & paste, as you would not get the full information of the image.
    When you paste you can't get the image info from the Links panel, but you can get resolution and color info either via the Preflight panel or by exporting to PDF and checking the image in Acrobat.
    Here I've pasted a 300ppi image, scaled it, and made a Preflight rule that catches any image under 1200ppi. The panel gives me the effective resolution of the pasted image as 556ppi. There are other workflow reasons not to paste—you loose the ability to easily edit the original and large file sizes—but pasting wouldn't cause a loss in effective resolution or change in color mode.

  • How to Load the data from excel file(Extension is .CSV) into the temp.table

    Hi
    How to Load the data from excel file(Extension is .CSV) into the temporary table of oracle in Forms11g.
    My Forms Version is - Forms [64 Bit] Version 11.1.2.0.0 (Production)
    Kindly Suggest the Solution.
    Regards,
    Sachin

    Hello Sachin,
    You can use the following metalink note:How to Read Data from an EXCEL Spreadsheet into a Form Using Webutil Client_OLE2 (Doc ID 813535.1) and modify it a little bit.
    Instead of copy values into forms you can save them in your temporary table.
    Kind regards,
    Alex
    If someone's helpful or correct please mark it accordingly.

  • How do i convert a pdf into an xls or csv file

    how do i convert a pdf into an xls or csv file   ? thnx

    HI newapiary
    You can either use Adobe Acrobat or Adobe ExportPDF Online Service.
    Please Refer : https://www.acrobat.com/exportpdf/en_GB/convert-pdf-to-word.html

  • How to parse xml data into java component

    hi
    everybody.
    i am new with XML, and i am trying to parse xml data into a java application.
    can anybody guide me how to do it.
    the following is my file.
    //MyLogin.java
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    class MyLogin extends JFrame implements ActionListener
         JFrame loginframe;
         JLabel labelname;
         JLabel labelpassword;
         JTextField textname;
         JPasswordField textpassword;
         JButton okbutton;
         String name = "";
         FileOutputStream out;
         PrintStream p;
         Date date;
         GregorianCalendar gcal;
         GridBagLayout gl;
         GridBagConstraints gbc;
         public MyLogin()
              loginframe = new JFrame("Login");
              gl = new GridBagLayout();
              gbc = new GridBagConstraints();
              labelname = new JLabel("User");
              labelpassword = new JLabel("Password");
              textname = new JTextField("",9);
              textpassword = new JPasswordField(5);
              okbutton = new JButton("OK");
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 5;
              gl.setConstraints(labelname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 5;
              gl.setConstraints(textname,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 10;
              gl.setConstraints(labelpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 2;
              gbc.gridy = 10;
              gl.setConstraints(textpassword,gbc);
              gbc.anchor = GridBagConstraints.NORTHWEST;
              gbc.gridx = 1;
              gbc.gridy = 15;
              gl.setConstraints(okbutton,gbc);
              Container contentpane = getContentPane();
              loginframe.setContentPane(contentpane);
              contentpane.setLayout(gl);
              contentpane.add(labelname);
              contentpane.add(labelpassword);
              contentpane.add(textname);
              contentpane.add(textpassword);
              contentpane.add(okbutton);
              okbutton.addActionListener(this);
              loginframe.setSize(300,300);
              loginframe.setVisible(true);
         public static void main(String a[])
              new MyLogin();
         public void reset()
              textname.setText("");
              textpassword.setText("");
         public void run()
              try
                   String text = textname.getText();
                   String blank="";
                   if(text.equals(blank))
                      System.out.println("First Enter a UserName");
                   else
                        if(text != blank)
                             date = new Date();
                             gcal = new GregorianCalendar();
                             gcal.setTime(date);
                             out = new FileOutputStream("log.txt",true);
                             p = new PrintStream( out );
                             name = textname.getText();
                             String entry = "UserName:- " + name + " Logged in:- " + gcal.get(Calendar.HOUR) + ":" + gcal.get(Calendar.MINUTE) + " Date:- " + gcal.get(Calendar.DATE) + "/" + gcal.get(Calendar.MONTH) + "/" + gcal.get(Calendar.YEAR);
                             p.println(entry);
                             System.out.println("Record Saved");
                             reset();
                             p.close();
              catch (IOException e)
                   System.err.println("Error writing to file");
         public void actionPerformed(ActionEvent ae)
              String str = ae.getActionCommand();
              if(str.equals("OK"))
                   run();
                   //loginframe.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    hi, thanks for ur reply.
    i visited that url, i was able to know much about xml.
    so now my requirement is DOM.
    but i dont know how to code in my existing file.
    means i want to know what to link all my textfield to xml file.
    can u please help me out. i am confused.
    waiting for ur reply

  • How to write the JTables Content into the CSV File.

    Hi Friends
    I managed to write the Database records into the CSV Files. Now i would like to add the JTables contend into the CSV Files.
    I just add the Code which Used to write the Database records into the CSV Files.
    void exportApi()throws Exception
              try
                   PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
                   System.out.println("Connected");
                   stexport=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                   rsexport=stexport.executeQuery("Select * from IssuedBook ");
                   ResultSetMetaData md = rsexport.getMetaData();
                   int columns = md.getColumnCount();
                   String fieldNames[]={"No","Name","Author","Date","Id","Issued","Return"};
                   //write fields names
                   String rec = "";
                   for (int i=0; i < fieldNames.length; i++)
                        rec +='\"'+fieldNames[i]+'\"';
                        rec+=",";
                   if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
                   writing.println(rec);
                   //write values from result set to file
                    rsexport.beforeFirst();
                   while(rsexport.next())
                        rec = "";
                         for (int i=1; i < (columns+1); i++)
                             try
                                    rec +="\""+rsexport.getString(i)+"\",";
                                    rec +="\""+rsexport.getInt(i)+"\",";
                             catch(SQLException sqle)
                                  // I would add this System.out.println("Exception in retrieval in for loop:\n"+sqle);
                         if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
                        writing.println(rec);
                   writing.close();
         }With this Same code how to Write the JTable content into the CSV Files.
    Please tell me how to implement this.
    Thank you for your Service
    Jofin

    Hi Friends
    I just modified my code and tried according to your suggestion. But here it does not print the records inside CSV File. But when i use ResultSet it prints the Records inside the CSV. Now i want to Display only the JTable content.
    I am posting my code here. Please run this code and find the Report.csv file in your current Directory. and please help me to come out of this Problem.
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class Exporting extends JDialog implements ActionListener
         private JRadioButton rby,rbn,rbr,rbnore,rbnorest;
         private ButtonGroup bg;
         private JPanel exportpanel;
         private JButton btnExpots;
         FileReader reading=null;
         FileWriter writing=null;
         JTable table;
         JScrollPane scroll;
         public Exporting()throws Exception
              setSize(550,450);
              setTitle("Export Results");
              this.setLocation(100,100);
              String Heading[]={"BOOK ID","NAME","AUTHOR","PRICE"};
              String records[][]={{"B0201","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0202","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0203","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0204","PRIAM","SELVI","1354"},
                               {"B0205","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0206","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0207","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0208","PRIAM","SELVI","1354"}};
              btnExpots= new JButton("Export");
              btnExpots.addActionListener(this);
              btnExpots.setBounds(140,200,60,25);
              table = new JTable();
              scroll=new JScrollPane(table);
              ((DefaultTableModel)table.getModel()).setDataVector(records,Heading);
              System.out.println(table.getModel());
              exportpanel= new JPanel();
              exportpanel.add(btnExpots,BorderLayout.SOUTH);
              exportpanel.add(scroll);
              getContentPane().add(exportpanel);
              setVisible(true);
          public void actionPerformed(ActionEvent ae)
              Object obj=ae.getSource();
              try {
              PrintWriter writing= new PrintWriter(new FileWriter("Report.csv"));
              if(obj==btnExpots)
                   for(int row=0;row<table.getRowCount();++row)
                             for(int col=0;col<table.getColumnCount();++col)
                                  Object ob=table.getValueAt(row,col);
                                  //exportApi(ob);
                                  System.out.println(ob);
                                  System.out.println("Connected");
                                  String fieldNames[]={"BOOK ID","NAME","AUTHOR","PRICE"};
                                  String rec = "";
                                  for (int i=0; i <fieldNames.length; i++)
                                       rec +='\"'+fieldNames[i]+'\"';
                                       rec+=",";
                                  if (rec.endsWith(",")) rec=rec.substring(0, (rec.length()-1));
                                  writing.println(rec);
                                  //write values from result set to file
                                   rec +="\""+ob+"\",";     
                                   if (rec.endsWith(",")) rec=rec.substring(0,(rec.length()-1));
                                   writing.println(rec);
                                   writing.close();
         catch(Exception ex)
              ex.printStackTrace();
         public static void main(String arg[]) throws Exception
              Exporting ex= new Exporting();
    }Could anyone Please modify my code and help me out.
    Thank you for your service
    Cheers
    Jofin

  • How to Parse a string into an XML DOM ?

    Hi,
    I want to parse a String into an XML DOM. Not able to locate any parser which supports that. Any pointers to this?

    Download Xerces from xml.apache.org. Place the relevant JAR's on your classpath. Here is sample code to get a DOM document reference.
    - Saish
    public final class DomParser extends Object {
         // Class Variables //
         private static final DocumentBuilder builder;
         private static final String JAXP_SCHEMA_LANGUAGE =
             "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
         /** W3C schema definitions */
         private static final String W3C_XML_SCHEMA =
             "http://www.w3.org/2001/XMLSchema";
         // Constructors //
         static {
              try {
                   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                   factory.setNamespaceAware(true);
                   factory.setValidating(true);
                   factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                   builder = factory.newDocumentBuilder();
                   builder.setErrorHandler(new ErrorHandler() {
                       public void warning(SAXParseException e) throws SAXException {
                           System.err.println("[warning] "+e.getMessage());
                       public void error(SAXParseException e) throws SAXException {
                           System.err.println("[error] "+e.getMessage());
                       public void fatalError(SAXParseException e) throws SAXException {
                           System.err.println("[fatal error] "+e.getMessage());
                           throw new XmlParsingError("Fatal validation error", e);
              catch (ParserConfigurationException fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document parser", fatal);
              catch (FactoryConfigurationError fatal) {
                   throw new ConfigurationError("Unable to create XML DOM document factory", fatal);
         private DomParser() {
              super();
         // Public Methods //
         public static final Document newDocument() {
              return builder.newDocument();
         public static final Document parseDocument(final InputStream in) {
              try {
                   return builder.parse(in);
              catch (SAXException e) {
                   throw new XmlParsingError("SAX exception during parsing.  Document is not well-formed or contains " +
                        "illegal characters", e);
              catch (IOException e) {
                   throw new XmlParsingError("Encountered I/O exception during parsing", e);
    }- Saish

  • How to generate graphs from csv file and show on remote clients?

    Hi,
    I have set of csv files. Each file has 104 parameters. From these parameters different graphs have to be generated and displayed to remote clients thru tomcat.
    Can anyone tell me how to do that?
    cheers,
    its reeju

    it's very easy to load the CSV into java objects. Once you have done that why not use the Java2D API to draw your graphs and then use the Sun JPG encoder tools to write out a jpg stream back to the browser (you will need to set the content type for jpg).

  • How to pass a JavaScript variable into a java method

    I would like to know how to pass a JavaScript variable into a java method with in a <% %> tag inside a JSP file like so:
    <%@ page contentType="text/html;charset=windows-1252"%>
    <html>
    <head>
    <script LANGUAGE="JavaScript">
    myValue = someDynamicValue;
    <% System.out.println(myValue)%>
    </script>
    </head>
    <body>
    </body>
    </html>
    obviously "System.out.println(myValue)" will not work because myValue is seen as a java variable and not a JavaScript variable.
    I would like to know how to let the jsp file, that I wrote in the above code, see myValue as a JavaScript variable and not a java variable so that I can pass it to a java method.
    NOTE: the java method does not have to be a println() method, it can be any method of my choice.
    NOTE: someDynamicValue is a JavaScript value that can dynamically change

    I don't believe you can. JSPs are really just elaborate templates that an engine such as Tomcat parses and generates an HTML page based on. That page is then displayed to the user. By the time you want to use some function in Javascript, the JSP has already been parsed and generated.
    Basically, Javascript and JSPs can't talk to each other. One's server-side and the other is client-side.

  • How do I compare two csv files and not disable the user if the username is found in the 2nd file using powershell?

    Hi Guys
    I have two csv files with the following headers and I need to import both files into the script to check whether the StaffCode is present in the Creation/Renewal of Contract csv in a DisableAccount Script so I can stop any action to disable the account as
    the staff has renewed the contract with the company so the account should not be disabled.
    However my accounts are still being disabled. I am not sure now to construct the query so that it detects that the account is to be left alone if the staffcode is present in both files
    I does recognize that the $staffcodeN in the renewal file matches the $staffcode in the termination file
    but still proceeds to disable or set an expiry date to the account anyway based on the termination file. 
    How do I stop it from doing that?
    1)In the Creation/Renewal of contract file the following headers are present
         -  TranCode,StaffCode,LastName,FirstName,SocialSecurityNo,DateJoin,Grade,Dept,LastUpdateDate,EffectiveDate
    2)In the Disable of contract file the following headers are present
        - TranCode,StaffCode,LastName,FirstName,SocialSecurityno,LastDateWorked,Grade,Dept,LastUpdateDate,
    My data is not very clean , I have a-lot of special characters such as = , ' ,/ and \ characters to remove first before i can compare the data
    Thanks for the help in advance.
    Yours Sincrely
    Vicki
    The following is a short snippet of the code 
    $opencsv = import-csv "D:\scripts\Termination.csv"
    $opencsv2 = import-csv "D:\scripts\RenewContractandNewStaff.csv"
    foreach ($usertoaction in $opencsv) 
    $Trancode = $usertoactionTranCode
    $StaffCode = $usertoaction.StaffCode.replace("=","").replace('"','')
    $LastName = [string]$usertoaction.LastName.Replace("/","\/").Replace(",","\,")
    $FirstName = [string]$usertoaction.FirstName.Replace("/","\/").Replace(",","\,")
    $socialsecurityno = $usertoaction.SocialSecurityNo.replace("=","").replace('"','')
    $DateJoin = $usertoaction.DateJoin.replace("=","").replace('"','')
    $LastDateWorked = $usertoaction.LastDateWorked.replace("=","").replace('"','')
    $Grade = [string]$usertoaction.Grade
    $Dept = [string]$usertoaction.Dept
    $LastUpdateDate = $usertoaction.LastUpdateDate.replace("=","").replace('"','')
    $AccountExpiry = [datetime]::Now.ToString($LastDateWorked)
    foreach ($usertoaction2 in $opencsv2) 
    $TrancodeN = $usertoaction2.TranCode
    $StaffCodeN = $usertoaction2.StaffCode.replace("=","").replace('"','')
    $socialsecurityNoN= $usertoaction2.SocialSecurityNo.replace("=","").replace('"','')
    $DateJoinN = $usertoaction2.DateJoin.replace("=","").replace('"','')
    $GradeN = [string]$usertoaction2.Grade
    $DeptN = $usertoaction2.Dept
    $LastUpdateDate = $usertoaction.LastUpdateDate.replace("=","").replace('"','')
    $EffectiveDate = $usertoaction.EffectiveDate.replace("=","").replace('"','')
    $LastName2 = [string]$usertoaction2.LastName.Replace(",", "").Replace("/","").trim()
    $FirstName2 = [string]$usertoaction2.FirstName.Replace("/","").trim()
    # Use DirectorySearcher to find the DN of the user from the sAMAccountName.
    $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
    $Root = $Domain.GetDirectoryEntry()
    $Searcher = [System.DirectoryServices.DirectorySearcher]$Root
    $Searcher.Filter = "(sAMAccountName=$samaccountname)"
    $doesuserexist1 = $Searcher.Findall()
    if ($doesuserexist1 -eq $Null)
    {Write-Host $samaccountname "account does not exist"}
    elseif ($StaffCodeN -match $staffcode)
    write-host "user has renewed the contract, no action taken"
    else
    if(($lastupdatedate -ne $null)-or($LastDateWorked -ne $null))
                        write-host "Setting Account Expiry to"$accountexpirydate
    #$ChangeUser.AccountExpires = $accountexpirydate
               #$Changeuser.setinfo()
    if ($UserMailforwarding -ne $null)
    #Set Account expiry date to Last Date Worked
    # $ChangeUser.AccountExpires = $accountexpirydate
    # $Changeuser.setinfo()
     write-host "staff" $displayname "with staff employee no" $samaccountname "has                          
    mailforwarding" 
    Write-host "Please disable the account manually via Active Directory Users & Computers and 
    Elseif ($accountexpirydate -lt $todaysdate)
    #disable the account

    Hi Vicki,
    This Forum has an insert-codeblock function. Using it will make your script far more readable
    Your script is missing some parts, it is impossible to follow the problem.
    You are performing the same string cleaning action on $opencsv2 for each element in $opencsv, when doing it once should suffice. Why not start it all by cleaning the values and storing the cleaned values in new arrays?
    The Compare-Object function is great, why not take it out for a stroll on these lists, it might just safe you lots of unnecessarily complicated code ...
    You are creating a new $Domain, $Root and $Searcher object each iteration, when doing it once should suffice. Probably not much of a time-saver, but every little thing contributes.
    Try pinpointing the problem by doing extensive logging, not only by writing which action was taken, but writing the inidividual information (variables, mostly) before evaluation occurs. Your if/elseif/else looks sound, so if it's still not doing what you
    want, the ingoing data must be different from what you think should be there.
    Cheers,
    Fred
    There's no place like 127.0.0.1

  • How to generate a second csv file with different report columns selected?

    Hi. Everybody:
    How to generate a second csv file with different report columns selected?
    The first csv file is easy (report attributes -> report export -> enable CSV output Yes). However, our users demand 2 csv files with different report columns selected to meet their different needs.
    (The users don't want to have one csv file with all report columns included. They just want to get whatever they need directly, no extra columns)
    Thank you for any help!
    MZ

    Hello,
    I'm doing it usually. Typically example would be in the report only the column "FIRST_NAME" and "LAST_NAME" displayed whereas
    in the csv exported with the UTL_FILE the complete address (street, housenumber, additions, zip, town, state ... ) is written, these things are needed e.g. the form letters.
    You do not need another page, just an additional button named e.g. "export_to_csv" on your report page.
    The csv export itself is handled from a plsql procedure "stored procedure" ( I like to have business logic outside of apex) which is invoked by pressing the button "export_to_csv". Of course the stored procedure can handle also parameters
    An example code would be something like
    PROCEDURE srn_brief_mitglieder (
         p_start_mg_nr IN NUMBER,
         p_ende_mg_nr IN NUMBER
    AS
    export_file          UTL_FILE.FILE_TYPE;
    l_line               VARCHAR2(20000);
    l_lfd               NUMBER;
    l_dateiname          VARCHAR2(100);
    l_datum               VARCHAR2(20);
    l_hilfe               VARCHAR2(20);
    CURSOR c1 IS
    SELECT
    MG_NR
    ,TO_CHAR(MG_BEITRITT,'dd.mm.yyyy') AS MG_BEITRITT ,TO_CHAR(MG_AUFNAHME,'dd.mm.yyyy') AS MG_AUFNAHME
    ,MG_ANREDE ,MG_TITEL ,MG_NACHNAME ,MG_VORNAME
    ,MG_STRASSE ,MG_HNR ,MG_ZUSATZ ,MG_PLZ ,MG_ORT
    FROM MITGLIEDER
    WHERE MG_NR >= p_start_mg_nr
    AND MG_NR <= p_ende_mg_nr
    --WHERE ROWNUM < 10
    ORDER BY MG_NR;
    BEGIN
    SELECT TO_CHAR(SYSDATE, 'yyyy_mm_dd' ) INTO l_datum FROM DUAL;
    SELECT TO_CHAR(SYSDATE, 'hh24miss' ) INTO l_hilfe FROM DUAL;
    l_datum := l_datum||'_'||l_hilfe;
    --DBMS_OUTPUT.PUT_LINE ( l_datum);
    l_dateiname := 'SRNBRIEF_MITGLIEDER_'||l_datum||'.CSV';
    --DBMS_OUTPUT.PUT_LINE ( l_dateiname);
    export_file := UTL_FILE.FOPEN('EXPORTDIR', l_dateiname, 'W');
    l_line := '';
    --HEADER
    l_line := '"NR"|"BEITRITT"|"AUFNAHME"|"ANREDE"|"TITEL"|"NACHNAME"|"VORNAME"';
    l_line := l_line||'|"STRASSE"|"HNR"|"ZUSATZ"|"PLZ"|"ORT"';
         UTL_FILE.PUT_LINE(export_file, l_line);
    FOR rec IN c1
    LOOP
         l_line :=  '"'||rec.MG_NR||'"';     
         l_line := l_line||'|"'||rec.MG_BEITRITT||'"|"' ||rec.MG_AUFNAHME||'"';
         l_line := l_line||'|"'||rec.MG_ANREDE||'"|"'||rec.MG_TITEL||'"|"'||rec.MG_NACHNAME||'"|"'||rec.MG_VORNAME||'"';     
         l_line := l_line||'|"'||rec.MG_STRASSE||'"|"'||rec.MG_HNR||'"|"'||rec.MG_ZUSATZ||'"|"'||rec.MG_PLZ||'"|"'||rec.MG_ORT||'"';          
    --     DBMS_OUTPUT.PUT_LINE (l_line);
    -- in datei schreiben
         UTL_FILE.PUT_LINE(export_file, l_line);
    END LOOP;
    UTL_FILE.FCLOSE(export_file);
    END srn_brief_mitglieder;Edited by: wucis on Nov 6, 2011 9:09 AM

Maybe you are looking for

  • How to calculate the rotation degree of tick marks

    Hello Again, Thanks to so much help that I received here, I've been able to move right along in learning how to perform my job digitally instead of with an old camera.  In my last discussion, I learned out to make the tick marks using copies and rota

  • How to specify the download file name??

    Hi guys~~~ I have servlet which can generate a *.pdf file,I found if I didn't setContentType="application/pdf",I can download it!!But the download file name is my servlet file name.If I want to change the download file name,How do I do???? thanx a lo

  • On at selection-screen event

    hi, i have two fields in seelction screen .if i enter delivery number on selection screen field automatically delivery date to filled in second field of selection screen. how it solved..

  • Compare fields in collection model to display which fields differ

    Hi all I have a previous post, which I may not have clearly enough stated my objective, and hence I feel as I may have been given an incorrect directive. Anyway, I aim to be able to compare fields in collection model to display which fields differ be

  • Qulaity Certificate "Output Type " for delivery

    How does the working of Output Type LQCA & LQCB differ ?