Excel Python之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
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值