Question
· May 4, 2017

Export Global in CSV File

Hi All,

I need urgent help,

I want to export the values from Global to CSV file.

Values are in global are :

^Global1(1)="1,2,3,4"
^Global1(2)="5,6,7,8"
.
.
.
^Global1(n)="n,n,n,n"

I want output in CSV File as:
1,2,3,4
5,6,7,8
.
.
.
n,n,n,n

I made a class:

ClassMethod ExportNewSchemaGlobals(pFile)
{
    Set ary("^Global1")=""
    Set pFile = "C:/Test.csv"
      
    Set ary = ##class(%Library.Global).Export(,.ary,pFile)
}

Discussion (5)2
Log in or sign up to continue

You can roll your own export function in a few lines of code and tailor it to your specific needs, something like..

ClassMethod Export(pGlobal, pFile)
{
    set file=##class(%File).%New(pFile)
    do file.Open("WN")
    set key=$order(@pGlobal@(""))
    while key'="" {
        do file.WriteLine(@pGlobal@(key))
        set key=$order(@pGlobal@(key))
    }
    do file.%Save()
}

and call it like so...

do ##class(Foo.CSVUtil).Export("^foo","C:\Temp\foo.csv")

(its a 30 second hack so might need some tweaking, also assumed no CSV escaping needed since commas are already used in the data.)

Just to make it as simple as possible as I am guessing you are new to Caché

ClassMethod Export(pGlobal, pFile)
{
    set file=##class(%File).%New(pFile)
    do file.Open("WN")
    set key=$order(^Global1(""))
    while key'="" {
        do file.WriteLine(^Global1key))
        set key=$order(^Global1(key))
    }
    do file.%Save()
}

$ORDER() is a command that returns the next defined subscript value.  When you pass in "" it returns the first defined subscript value, 1 in your case.   After writing the value of ^Global1(n) to the file the final $ORDER() will return "" indicating there are no more defined subscript values.

for more details see our docs for $ORDER()

Hi Confused.  In your sample output you show it like so:

I want output in CSV File as:
1,2,3,4
5,6,7,8
.
.
.
n,n,n,n

Just to be sure what you're asking for, you do not want the output to contain anything from the global name or the global subscript?  So you do not want to see anything like:

^GLOBAL1(1)="1,2,3,4"
^GLOBAL1(2)="5,6,7,8"

- or -

^GLOBAL1(1)
1,2,3,4
^GLOBAL1(2)
5,6,7,8

- or -

1=1,2,3,4
2=5,6,7,8

Anyway, if you're on a Windows based system, you might have to change the file name to use the backslash rather than the forward slash, so:

Set pFile = "C:/Test.csv"

- would become -

Set pFile = "C:\Test.csv"

But to give yourself a better chance of not running afoul of directory permissions issues, you might be better to use:

Set pFile = $System.Util.GetEnviron("TEMP")_"\Test.csv"

And the for a quick and dirty COS way of outputting the the values from a TERM session (you should be able to copy/paste this code into a Cache TERM session):

Set pFile = $System.Util.GetEnviron("TEMP")_"\Test.csv"
Open pFile:"NW":0
If $T Set sub="" For  Set sub=$Order(^GLOBAL1(sub)) Quit:sub=""  Use pFile Write ^GLOBAL1(sub),! Use 0
Close pFile

Hope this helps.