Xlwings学习笔记
一、Python基本
1.1 延时函数
import time
time.sleep(10) #延时10秒
1.2 代码换行
1.2.1 反斜杠 \ ——不影响输出结果的代码换行
同时适用于字符串和代码
示例1
a = b + c + d + \
e + f + g + h
示例2.a
print('a b c d e f' \
'g h i j k')
运行结果:
a b c d e fg h i j k
示例2.b
print('a b c d e f \
g h i j k')
运行结果:
a b c d e f g h i j k
(注意 f 和 g 之间有无空格的区别)
1.2.2 三引号 ‘’’ ‘’’ —— 令字符串的打印结果换行
仅适用于字符串
print(''' a b c d e
f g h i j''')
运行结果:
a b c d e
f g h i j
注意:使用时须小心行尾的反斜杠会导致打印结果换行失败
print ('''a b c d e \
f g h i j''')
运行结果
a b c d e f g h i j
Note:
1、在字符串前加 r 也可以令换行符、缩进符等失效
print (r"a\ta\na")
运行结果:
a\ta\na
print ("a\ta\n")
运行结果:
a a
a
1.3 判断Excel文件是否已经打开
运行xlwings打开excel文件时,如果该文件已经打开则会报错
方法一、通过临时文件判断Excel文档的占用情况。
(以下方法仅限于本地文件,对Onedrive等网络位置上的文档无效。)
import os
import xlwings as xw
FilePath = 'C:\\Documents\\'
FileName = 'XXXX.xlsx'
def excel_is_open(file_path,file_name):
temp_file = file_path + '~$' + file_name
if os.path.exists(temp_file) : return True
else : return False
if not excel_is_open(FilePath,FileName):
xw.books.open(FilePath+FileName)
方法二、通过捕获异常以避免程序停止运行
from pythoncom import com_error
import xlwings as xw
FilePath = 'C:\\Documents\\'
FileName = 'XXXX.xlsx'
com_error_msg_01 = "Verify that the file has not been corrupted and that the file extension matches the format of the file"
com_error_msg_02 = r"The file name or path does not exist.\n• The file is being used by anothe