python (module) xlwt

1. Introduction to xlwt

xlwt only supports excel in xls format, and can only create xls and then write to xls files .

Two, xlwt syntax

1. Module installation

pip3 install xlwt

2. Module import

import xlwt

3. Write content to the xls file

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')

insert image description here

4. Set the format of the written file

Setting the cell style in xlwt is mainly done through the XFStyle class. The correspondence between the attributes in the XFStyle class and the cell attributes is as follows:

XFStyle property name Corresponding cell properties value type
num_format_str Data Format str
font font Font class instance
alignment align Alignment class instance
borders frame Borders class instance
pattern filling Pattern class instance
protection Protect Protection class instance

4.1 Font Settings (font)

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')

insert image description here

illustrate:

  • The ratio of font size
    and excel font size is 1:20. If you need a font size of 15, you need to set it to 300

  • Font color comparison chart
    insert image description here

4.2 Background color settings (pattern)

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')

insert image description here

4.3 Border settings (borders)

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')

insert image description here

4.4 Alignment settings (alignment)

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')

insert image description here

4.5 Cell format (num_format_str)

insert image description here
insert image description here

Example :
Date data is written to excel, and the cell is in a custom date format

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')

insert image description here

insert image description here

4.6 Column width and row height

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')

insert image description here

4.7 Multi-row and column merge write

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')

insert image description here

3. Example application

Function description:
Fetch data from database, write to xlsx, and send email.

Code:

# 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)


Effect:
insert image description here
insert image description here
insert image description here

4. References

The xlwt module of the python module

Guess you like

Origin blog.csdn.net/shammy_feng/article/details/124128706