Abuzar Anis
Abuzar Anis

Reputation: 45

writing output to a excel in different column

Hi I am using tcl to write output a xls file. however I am succeeding in writing the output to a xls file in one column but what i want to split and write to two different column at the sane time . My code which is writing to one column only is working fine:

 set fh [open $e w]
  while {[llength $c]} {
    set name [lindex $c 0]
    set c [concat [glob -nocomplain -directory [lindex $c 0] -type d *] [lrange $c 1 end]]
    set filesofDirectory [glob -nocomplain -directory $name -type f *]

        if { [llength $filesofDirectory] > 0 && $d == "fftc"} {
                set x "number of files in $name is  [llength $filesofDirectory]"


                puts $fh [join $x ]
        } 
    }
    close $fh

However when I modified the same code to have the output :

 set fh [open $e w]
  while {[llength $c]} {
    set name [lindex $c 0]
    set c [concat [glob -nocomplain -directory [lindex $c 0] -type d *] [lrange $c 1 end]]
    set filesofDirectory [glob -nocomplain -directory $name -type f *]

        if { [llength $filesofDirectory] > 0 && $d == "fftc"} {
                set x "number of files in $name"
                set y [llength $filesofDirectory]

                puts $fh [join $x "," $y]
        } 
    }
    close $fh

Please suggest the workaround

Upvotes: 0

Views: 184

Answers (1)

Peter Lewerin
Peter Lewerin

Reputation: 13272

To dump a directory breakdown into a CSV file that can be used in Excel, this code ought to work:

package require csv

set c .
set d fftc
set e foo.csv

proc glob2csv {c d fh} {
    foreach name $c {
        if {[file isdirectory $name]} {
            set n [llength [glob -nocomplain -directory $name -type f *]]
            if {$n > 0 && $d eq "fftc"} {
                chan puts $fh [csv::join [list "number of files in $name is" $n]]
            }
            glob2csv [glob -nocomplain -directory $name -type d *] $d $fh
        }
    }
}

try {
    open $e w
} on ok fh {
    glob2csv $c $d $fh
} finally {
    catch {chan close $fh}
}

I'm making a lot of uncomfortable assumptions here since I don't really know what your code is about. You might want to use the optional arguments to csv::join to tweak the format of the CSV file. In my locale, for instance, I need to set the separator character to tab (\t) to avoid having Excel treat every line as a single string.

Documentation for the Tcllib CSV module

Documentation: catch, chan, file, foreach, glob, if, list, llength, open, package, proc, set, try

Upvotes: 1

Related Questions