xlwt仅支持 xls 格式的exce,只能新建xls后写入xls文件。
pip3 install xlwt
import xlwt
import xlwt
# 创建一个workbook对象,就相当于创建了一个Excel文件
workbook = xlwt.Workbook(encoding='utf-8',style_compression=0) # encoding:设置编码,可写中文;style_compression:是否压缩,不常用
# 创建一个sheet对象,相当于创建一个sheet页
worksheet = workbook.add_sheet('这是sheet1',cell_overwrite_ok=True) # cell_overwrite_ok:是否可以覆盖单元格,默认为False
# 向sheet页中添加数据:worksheet.write(行,列,值)
worksheet.write(0,0,'我要发财啦') # 第1行第1列写入数据
# 将以上内容保存到指定的文件中
workbook.save('测试文件.xls')
xlwt 中设置单元格样式主要是通过 XFStyle 这个类来完成的,XFStyle 类中属性与单元格属性的对应关系如下:
XFStyle属性名 | 对应单元格属性 | 值类型 |
---|---|---|
num_format_str | 数据格式 | str |
font | 字体 | Font类实例 |
alignment | 对齐 | Alignment类实例 |
borders | 边框 | Borders类实例 |
pattern | 填充 | Pattern类实例 |
protection | 保护 | Protection类实例 |
import xlwt
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('这是sheet1')
style = xlwt.XFStyle()# 初始化样式
font = xlwt.Font()# 为样式创建字体(font)
# 指定字体的具体属性(仅列出常用属性)
font.name = '宋' # 指定字体
font.height = 300 # 和excel字体大小比例是1:20
font.bold = True # 字体是否加粗
font.underline = True # 字体是否下划线
font.struck_out = True # 字体是否有横线
font.italic = True # 是否斜体字
font.colour_index = 4 # 字体颜色
# 设定字体样式
style.font = font
# 向sheet页中添加数据
worksheet.write(0,0,'无样式文本')
worksheet.write(0,1,'有样式文本',style)
workbook.save('测试文件.xls')
说明:
import xlwt
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook .add_sheet('这是sheet1')
worksheet.write(0,0,'无样式文本')
# 初始化样式
style = xlwt.XFStyle()
# 1. 为样式创建字体(font)
font = xlwt.Font()
# 指定字体的具体属性(仅列出常用属性)
font.name = '宋' # 指定字体
font.height = 300 # 和excel字体大小比例是1:20
font.bold = True # 字体是否加粗
font.underline = True # 字体是否下划线
font.struck_out = True # 字体是否有横线
font.italic = True # 是否斜体字
font.colour_index = 4 # 字体颜色
# 设置style的各个属性的样式
style.font = font # 设定字体样式
worksheet.write(2,0,'有样式文本(字体样式)',style)
# 2. 为样式创建背景图案(pattern)
pattern = xlwt.Pattern()
# 指定背景颜色
pattern.pattern = xlwt.Pattern.SOLID_PATTERN # 设置背景颜色模式
pattern.pattern_fore_colour = 3 # 不同的值代表不同颜色背景
# 设置style的各个属性的样式
style.pattern = pattern # 设定背景图案样式
worksheet.write(4,0,'有样式文本(字体样式+背景图案样式)',style)
workbook .save('测试文件.xls')
import xlwt
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook .add_sheet('这是sheet1')
# 初始化样式
style = xlwt.XFStyle()
borders = xlwt.Borders()
# 设定边框属性
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
# 设定边框样式
style.borders = borders
# 写入数据
worksheet.write(0,0,'无样式文本')
worksheet.write(2,0,'有样式文本(边框样式)',style)
# 保存.xls
workbook.save('测试文件.xls')
import xlwt
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook .add_sheet('这是sheet1')
# 初始化样式
style = xlwt.XFStyle()
# 对齐方式的设置(alignment)
alignment = xlwt.Alignment()
# 设置具体的对齐方式 : vert代表垂直对齐方式;horz代表水平对齐方式
alignment.vert = 0x01 # 0x00 上端对齐;0x01 居中对齐(垂直方向上);0x02 底端对齐
alignment.horz = 0x03 # 0x01 左端对齐;0x02 居中对齐(水平方向上);0x03 右端对齐
# 自动换行
alignment.wrap = 1 # 自动换行
# 设定设定对齐方式
style.alignment = alignment
# 写入数据
worksheet.write(0,0,'无样式文本')
worksheet.write(2,0,'有样式文本(设定对齐方式)',style)
# 保存.xls
workbook.save('测试文件.xls')
举例:
日期数据写入excel,单元格为自定义的日期格式
import xlwt
from datetime import datetime
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook .add_sheet('这是sheet1')
date_str = '2022-04-12'
style = xlwt.XFStyle()
num_format_str = 'yyyy/MM/dd'
style.num_format_str = num_format_str
# 写入数据
worksheet.write(0,0,date_str)
worksheet.write(2,0,datetime.strptime(date_str,'%Y-%m-%d').date(),style)
# 保存.xls
workbook.save('测试文件.xls')
import xlwt
from datetime import datetime
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook .add_sheet('这是sheet1')
# 写入数据
worksheet.write(0,0,'我是个很长的字符')
worksheet.write(0,4,'我也是个很长的字符哦')
worksheet.col(4).width=256*20 # 设计第4列宽度
# 保存.xls
workbook.save('测试文件.xls')
import xlwt
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook .add_sheet('这是sheet1')
# 写入数据
worksheet.write(0,0,'无合并')
worksheet.write_merge(0, 3, 4, 7, '有合并')#1-4行,5-8列合并单元格
# 保存.xls
workbook.save('测试文件.xls')
功能描述:
从数据库取数,写入xlsx,并发送邮件。
代码实现:
# util为博主封装的模块
from util import config
from util.gmail import Mail
from util.gstring import convert_df_to_html
from util.logger import log
from util.db import get_db
import pandas as pd
import os
from datetime import datetime
import xlwt
def run(init_date):
#创建excel文件
new_excel = "6(1)班考试成绩单-" + init_date +".xls" # 附件
if os.path.exists(new_excel) :
os.remove(new_excel)
workbook = xlwt.Workbook(encoding='utf-8')
# 数据库连接
db = get_db("dbcenter")
# 数据库取数
log.info('开始从数据库取数...')
math_sql = f'''
select '张三' as name
,'6(1)班' as class
,'数学' as subject
,95 as score
,{init_date} as init_date
union all
select '李四' as name
,'6(1)班' as class
,'数学' as subject
,98 as score
,{init_date} as init_date
union all
select '王五' as name
,'6(1)班' as class
,'数学' as subject
,null as score
,{init_date} as init_date
'''
chinese_sql = f'''
select '张三' as name
,'6(1)班' as class
,'语文' as subject
,90 as score
,{init_date} as init_date
union all
select '李四' as name
,'6(1)班' as class
,'语文' as subject
,88 as score
,{init_date} as init_date
union all
select '王五' as name
,'6(1)班' as class
,'语文' as subject
,70 as score
,{init_date} as init_date
'''
sqls = [math_sql,chinese_sql]
sheets = ['数学成绩单','语文成绩单']
for i in range(0,len(sqls)) :
datas = db.query(sqls[i], {init_date : init_date})
df = pd.DataFrame(datas, columns=['name', 'class', 'subject', 'score', 'init_date'])
df["班主任"] = '王老师'
df["考试日期"] = datetime.strptime(init_date, '%Y%m%d').date()
df = df.rename(columns= {"name":"姓名","class":"班级","subject":"科目","score":"分数"})
order = ["考试日期","班级","班主任","姓名","科目","分数"]
df = df[order].fillna(0)#缺考分数为0
log.info(df)
datas = [tuple(xi) for xi in df.values]
excel_data = [tuple(order)] + datas
worksheet = workbook.add_sheet(sheets[i])
for i in range(0,len(excel_data)):
for j in range(0,len(excel_data[i])):
style = xlwt.XFStyle()
font = xlwt.Font()
font.name = '宋' # 指定字体
font.height = 220 # 字体大小
alignment = xlwt.Alignment()
alignment.horz = 0x02 # 对齐方式
if i == 0:
font.bold = True # 字体是否加粗
else:
if j == 0:
num_format_str = 'yyyy/MM/dd'
style.num_format_str = num_format_str
else:
pass
style.font = font
style.alignment = alignment
worksheet.col(j).width = 60*60 # 列宽
worksheet.write(i, j, excel_data[i][j], style)
workbook.save(new_excel)
#发邮件
#html = convert_df_to_html(df)
mail_config = config.get_config("email.send_fxm")# 发件人
mail = Mail(mail_config)
title = '6(1)班考试成绩单-' + init_date # 邮件标题
to_list = 'xxx.com' # 收件人
mail.send_email(to_list, title,content_text = '各位家长你们好,6(1)班'+ init_date + '日考试成绩单详见附件!', attachment_list=[new_excel])
if __name__ == "__main__":
init_date = '20220412'
run(init_date)
python模块 之 xlwt模块