创建Excel表格
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName :
# @Time :2022/05/17
# @Author :运维@小兵
# @Function :创建Excel表格
# @Excute :
import os,xlwt
workdir = os.path.dirname(os.path.abspath(__file__))
# 设置标题样式
def set_title_style(blod=False,underline=False):
style = xlwt.XFStyle() # 初始化样式
font = xlwt.Font() # 为样式创建字体
font.name = "Calibri" # 字体类型
font.height = 20 * 11 # 20为衡量单位,11为字号
font.bold = blod # 是否加粗
font.underline = underline # 是否添加下划线
style.font = font
return style
# 创建Excel文件
def create_excel():
file_name = "test.xls"
file_path = os.path.join(workdir,file_name)
#创建workbook和sheet对象
workboot = xlwt.Workbook(encoding='utf-8')
worksheet = workboot.add_sheet('test') # 设置工作表的名字
worksheet.col(0).width = 256 * 20 # 设置第一列列宽, 256为衡量单位,10表示10个字符宽度
worksheet.col(1).width = 256 * 10
worksheet.col(2).width = 256 * 10
#写入Excel标题
row0 = ["姓名","性别","年龄"]
for i in range(len(row0)):
worksheet.write(0,i,row0[i],set_title_style(True))
age_link = 'HYPERlink("https://www.baidu.com";18)' # 设置超链接
worksheet.write(1, 0, "运维@小兵", set_title_style())
worksheet.write(1, 1, "男", set_title_style())
worksheet.write(1, 2, xlwt.Formula('%s' % age_link), set_title_style(False, True))
workboot.save(file_path)
if __name__ == '__main__':
try:
create_excel()
except Exception as e:
print('[ERROR] %s' % e)
参考文章
xlwt模块详解–设置列宽、行高xlwt设置excel字体、对齐方式、边框、颜色、背景色