TCL twapi Excel写:文本格式

时间:2018-02-10 19:04:46

标签: excel tcl

这很奇怪。我使用twapi包(4.1.27,64bit)将数据写入Excel。在写数据之前,我将单元格格式化为文本,当实际数据为'1233566706'时,我仍然看到'1.23E + 09'等值。我的代码如下。

类似的代码在tcom包(32位包)中工作正常,因此它与我正在使用的Excel版本没有问题。如何在Excel单元格中显示实际值? (在这种情况下为1233566706)

#twapi 4.1.27
package require twapi

set excelOutFile {C:\AA\1.xlsx}

set application [::twapi::comobj Excel.Application]
set workbooks [$application Workbooks]

set workbook [$workbooks Add]
set worksheets [$workbook Worksheets]
set worksheet [$worksheets Item [expr 1]]
$worksheet Activate
set cells [$worksheet Cells]

set range [$worksheet Range "A1" "A1"]
#change format to Text
$range NumberFormat "@"

$cells Item [expr 1] [expr 1] "1233566706"

$workbook SaveAs $excelOutFile
$application Quit
$cells -destroy 
$worksheet -destroy 
$worksheets -destroy 
$workbook -destroy 
$workbooks -destroy 
$application -destroy
unset application

1 个答案:

答案 0 :(得分:0)

您的脚本适用于Tcl 8.6.8(64位),TWAPI 4.1.27和Excel2013。默认情况下,该单元格显示“ 1.23E + 09”,但是如果您展开该列,它将正确显示显示“ 1233566706”:

enter image description here

我添加了对AutoFit的调用以自动执行此操作,并添加了销毁范围对象的调用,否则Excel无法退出:

#twapi 4.1.27
package require twapi

set excelOutFile {C:\AA\1.xlsx}

set application [::twapi::comobj Excel.Application]
set workbooks [$application Workbooks]

set workbook [$workbooks Add]
set worksheets [$workbook Worksheets]
set worksheet [$worksheets Item [expr 1]]
$worksheet Activate
set cells [$worksheet Cells]
set columns [$worksheet Columns]

set range [$worksheet Range "A1" "A1"]
#change format to Text
$range NumberFormat "@"

$cells Item [expr 1] [expr 1] "1233566706"
$columns AutoFit

$workbook SaveAs $excelOutFile
$application Quit
$range -destroy
$columns -destroy
$cells -destroy
$worksheet -destroy
$worksheets -destroy
$workbook -destroy
$workbooks -destroy
$application -destroy
unset application