首页 > 技术文章 > TCL:表格(xls)中写入数据

leonlipfsj 2016-04-28 22:38 原文

 1 intToChar.tcl
 2 
 3 # input a number : 1 to 32 , you will get a char A to Z
 4 #A-Z:1-32
 5 proc intToChar {int} {
 6     if {![string is integer $int]} {
 7         return "Please input a number!"
 8     } 
 9     if {![expr 0<$int&&32>$int]} {
10         return "Input a numer range 1 to 32!"
11     } 
12     set listChars [list A B C D E F G H I J K L M N O P Q R S T U V W X Y Z]
13     set intTemp [expr $int-1]
14     return [lindex $listChars $intTemp]
15 }
16 
17 #test
18 #return [intToChar 1]
19 
20 
21 intToChar.tcl
22 
23 package require tcom
24 source intToChar.tcl
25 proc xls_write {fileName date} {
26 #    if {[file exists $fileName]} {
27 #        return {File is existed !   Please delete or change the the of the file !}
28 #    }
29     if {""==$date} {
30         return "The date is NULL or '' !"
31     }
32 #    set fileName {D:/test.xlsx}
33     # 创建com实例,打开工作表
34     set application [::tcom::ref createobject "Excel.Application"]
35     $application Visible 1
36     set workbooks [$application Workbooks]
37     set workbook [$workbooks Add]
38     set worksheets [$workbook Worksheets]
39     #set worksheet [$worksheets Item "Sheet1"]
40     set worksheet [$worksheets Item [expr 1]]
41     set cells [$worksheet Cells]
42     
43     set exeFlag 1
44     
45     if {1==$exeFlag} {
46 #        set date {}
47         set dateRawLength [llength $date]
48         set rawIndex 0
49         while { $rawIndex < $dateRawLength } {
50             set dateColumnLength 0
51             set dateColumnLength [llength [lindex $date $rawIndex]]
52             set columnIndex 0
53             while { $columnIndex < $dateColumnLength } {
54                 [$cells Item [expr $rawIndex+1] [intToChar [expr $columnIndex+1]]] Value2 [lindex [lindex $date $rawIndex] $columnIndex]
55                 incr columnIndex
56             }
57             incr rawIndex
58         }
59     } 
60     #code not work like wanting
61 #    if {[regexp -all {\\|/} $fileName]} {
62 #        cd [file dirname $fileName]
63 #    } 
64     #save without asking
65     $application DisplayAlerts [expr 0]
66 #    $workbook SaveCopyAs {d://ts.xlsx}
67     $workbook SaveAs $fileName
68     $workbook Close
69     $application Quit
70 #    return [file join [file dirname $fileName] [file tail $fileName]]
71 }
72 #含路径的文件保存时,有时会失败,原因不详(xls默认保存路径:菜单"文件"-->"选项"-->"保存",查看路径)
73 set fileName {d:\testaaa.xlsx}
74 set date [list [list 1 2 3 4 5 6 7 8 9 10] [list a b c d e f g] [list nihao hello 你好 howAreYou?]]
75 #test 
76 return [xls_write $fileName $date]

 

推荐阅读