python win32com excel边框格式化

标签 python excel border win32com

我这里有一段代码实际上可以使用 python win32com 在 excel 中格式化边框。我担心的是格式化边框所需的时间。我试图在 excel 中记录一个宏以找出将其转置到我的脚本中所需的信息,但它没有用。

因此,我能做的最好的事情就是在 for range 循环中运行,我总是从第 3 行开始,直到名为 shn[1] 的行计数器以 1 为增量,从第 1 列到 10 以 1 为增量。从那里我使用“BorderAround()”,它工作正常但速度太慢。这是我的一段代码:

for shn in [("Beam-Beam", bb_row, bb_col), ("Beam-Col", bc_row, bc_col)]:
sheet = book.Worksheets(shn[0])
sheet.Range( "J3:DW3" ).Copy()
if shn[0] == "Beam-Col":
    sheet.Range( "J3:AA3" ).Copy()
sheet.Range( sheet.Cells( 4, 10 ), sheet.Cells( shn[1]-1, 10 )  ).PasteSpecial()
for mrow in xrange(3,shn[1],1):
    for mcol in xrange(1,10,1):
        sheet.Cells(mrow, mcol).BorderAround()#.Border(1)

我可以做些什么来用像 ==> sheet.Range( sheet.Cells(3,1), sheet.Cells(shn[1],10) ) 这样的范围来格式化边框吗?我尝试了“.Borders(11)”和“.Borders(12)”以及“.BorderAround()”,但只有“.BorderAround()”有效。

提前致谢。

最佳答案

嗯,你用的是什么excel?

这应该有效:

for shn in [("Beam-Beam", bb_row, bb_col), ("Beam-Col", bc_row, bc_col)]:
sheet = book.Worksheets(shn[0])
sheet.Range( "J3:DW3" ).Copy()
if shn[0] == "Beam-Col":
    sheet.Range( "J3:AA3" ).Copy()
## Set a variable named rng to the range
rng = sheet.Range( sheet.Cells( 4, 10 ), sheet.Cells( shn[1]-1, 10 )  )
rng.PasteSpecial()
## Using this range, we can now set its borders linestyle and weight
##  -> where 7 through 13 correspond to borders for xlEdgeTop,xlEdgeBottom,
##     xlEdgeRight, xlEdgeLeft, xlInsideHorizontal, and xlInsideVertical
##  -> LineStyle of 1 = xlContinous
##  -> Weight of 2 = xlThin
for border_id in xrange(7,13):
    rng.Borders(border_id).LineStyle=1
    rng.Borders(border_id).Weight=2
## And to finish just call
book.Close(True) # To close book and save
excel_app.Quit() # or some variable name established for the com instance

让我知道这对您有何帮助。

另外,如果将 excel 应用程序 Visible 设置为 False 或关闭屏幕更新,它可能会更快:

excel_app.Visible = False # This will not physically open the book
excel_app.ScreenUpdating = False # This will not update the screen on an open book
##
# Do Stuff...
##
# Just make sure when using the ScreenUpdating feature that you reenable it before closing
excel_app.ScreenUpdating = True

这样 excel 就不会为每次调用更新屏幕。

关于python win32com excel边框格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19095659/

相关文章:

javascript - jQuery 控制标签的边框颜色

Python PIL - 属性错误: 'NoneType' object has no attribute 'save'

css - Chrome - CSS 边框无法正常工作

python加载在不同文件夹中找到的相同包结构的模块

python - 需要一些关于如何编写日志解析器的想法

excel - VBA Workbooks.Open 导致 excel 崩溃

excel - Excel 数据透视表 MDX 速度慢?

python - Scrapy 通过 IP 地址爬取本地网站

python - 值错误: too many values to unpack while parsing the txt

python - 在工作表之间切换