python模块 XlsxWriter

最后都变了- 提交于 2020-03-02 02:08:58

介绍

Xlsx是python用来构造xlsx文件的模块,可以向excel2007+中写text,numbers,formulas 公式以及hyperlinks超链接。

可以完成xlsx文件的自动化构造,包括:

合并单元格,制作excel图表等功能:

 

 

 

xlsxWriter支持多种excle功能;与excel完美兼容;写大文件,速度快且只占用很小的内存空间

不支持读或者改现有的excel文件

安装

 pip install XlsxWriter

文档

https://xlsxwriter.readthedocs.io/contents.html

 

使用

import xlsxwriter

 # Create a workbook and add a worksheet.
 workbook = xlsxwriter.Workbook('Expenses02.xlsx')
 worksheet = workbook.add_worksheet()

 # Add a bold format to use to highlight cells.
 bold = workbook.add_format({'bold': True})

 # Add a number format for cells with money.
 money = workbook.add_format({'num_format': '$#,##0'})

 # Write some data headers.
 worksheet.write('A1', 'Item', bold)
 worksheet.write('B1', 'Cost', bold)

 # Some data we want to write to the worksheet.
 expenses = (
     ['Rent', 1000],
     ['Gas',   100],
     ['Food',  300],
     ['Gym',    50],
 )

 # Start from the first cell below the headers.
 row = 1
 col = 0

 # Iterate over the data and write it out row by row.
 for item, cost in (expenses):
     worksheet.write(row, col,     item)
     worksheet.write(row, col + 1, cost, money)
     row += 1

 # Write a total using a formula.
 worksheet.write(row, 0, 'Total',       bold)
 worksheet.write(row, 1, '=SUM(B2:B5)', money)

 workbook.close()

 

 

实例演示

写一个订单的demo

 

 

import xlsxwriter
import time
import datetime

workbook = xlsxwriter.Workbook('demo.xlsx',
                               {'constant_memory': True})  # 新建excel表
worksheet = workbook.add_worksheet('订单信息')  # 新建sheet(sheet的名称为"订单信息")

headings = ['订单编号', '付款时间', '订单人', '订单金额', '送货地址']   # 设置表头

expenses = [
    ['2020022921571600005', '2020-02-29 21:57:16', '张三', '5.00', '北京三里屯'],
    ['2020022920451600004', '2020-02-29 20:45:15', '李四', '25.80', '北京大望路'],
    ['2020022920451600035', '2020-03-29 19:45:15', '王五', '200.80', '北京清河'],
]

# 标签头格式
head_format = workbook.add_format({
    'bold': True,                 # 字体加粗
    'border': 1,                    # 单元格边框宽度
    'align': 'center',          # 对齐方式
    'valign': 'vcenter',         # 字体对齐方式
    'fg_color': '#CBCBFF',         # 单元格背景颜色
    'font_size': 12                # 字体大小

})

money_format = workbook.add_format(
    {'num_format': '#,##0.00', 'font_size': 10})  # 金钱格式
date_format = workbook.add_format(
    {'num_format': 'yyyy-mm-dd hh:mm:ss', 'font_size': 10})  # 时间格式
normal_fomat = workbook.add_format({'font_size': 10})  # 普通格式
# currency_format = workbook.add_format({'num_format': '#,##0.00'})
worksheet.set_column(0, len(headings) - 1, width=30)  # 设置单元格宽度

# 写表头
for index, val in enumerate(headings):
    worksheet.write(0, index, val, head_format)

# Start from the first cell below the headers.
row = 1
col = 0

# 写数据
for item, date_str, person, cost, addr in (expenses):
    # Convert the date string into a datetime object.
    # date = datetime.datetime.now() #mktime(time.strptime(date_str, "%Y-%m-%d
    # %H:%M:%S"))

    date = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
    num = float(cost)

    worksheet.write_string(row, col, item, normal_fomat)
    worksheet.write_datetime(row, col + 1, date, date_format)
    worksheet.write_string(row, col + 2, person, normal_fomat)
    worksheet.write_number(row, col + 3, num, money_format)
    worksheet.write_string(row, col + 4, addr, normal_fomat)
    row += 1

# 设置文本区格式
options = {
    'width': 256,
    'height': 50,
    'x_offset': 10,
    'y_offset': 10,

    'font': {'color': 'red',
             'size': 14},
    'align': {'vertical': 'middle',
              'horizontal': 'center'
              },
    # 'gradient': {'colors': ['#DDEBCF',
    #                         '#9CB86E',
    #                         '#156B13']},
}
# 插入文本区
worksheet.insert_textbox(row+1,col+1, '“订单明细”工作表查看商品详情',
                         options)


worksheet = workbook.add_worksheet('商品详情')  # 新建sheet(sheet的名称为"商品详情")

workbook.close()

 

在Flask中运用

@route_member.route("/export", methods=['GET'])
def export_records():
    """
    excel导出
    :return:
    """
    output = write_records()
    resp = make_response(output.getvalue())
    resp.headers["Content-Disposition"] = "attachment; filename=export_member%s.xlsx" %(getStrDate()+str(random.randint( 0,9999 )))
    resp.headers['Content-Type'] = 'application/x-xlsx'
    return resp



def write_records():
    """
    写excel数据
    :return:
    """
    query_sets = Member.query.order_by(Member.id.desc()).all()
    column_names = ['姓名', '性别', '状态']
    data_col = ['nickname', 'sex_desc', 'status_desc']
    excel_data = make_excel_list(query_sets, data_col)
    # app.logger.info(excel_data)

    # 创建数据流
    output = BytesIO()
    # 创建excel work book
    writer = pd.ExcelWriter(output, engine='xlsxwriter')
    workbook = writer.book
    # 创建excel sheet
    worksheet = workbook.add_worksheet('会员表')

    # 标签头格式
    head_format = workbook.add_format({
        'bold': True,  # 字体加粗
        'border': 1,  # 单元格边框宽度
        'align': 'center',  # 对齐方式
        'valign': 'vcenter',  # 字体对齐方式
        'fg_color': '#CBCBFF',  # 单元格背景颜色
        'font_size': 12  # 字体大小

    })

    normal_fomat = workbook.add_format({'font_size': 10})  # 普通格式
    worksheet.set_column(0, len(column_names) - 1, width=30)  # 设置单元格宽度
    col = 0
    row = 1
    # 写入列名
    for item in column_names:
        worksheet.write(0, col, item, head_format)
        col += 1

    # 写数据
    col = 0
    for nickname, sex_desc, status_desc in (excel_data):
        worksheet.write_string(row, col, nickname, normal_fomat)
        worksheet.write_string(row, col+1, sex_desc, normal_fomat)
        worksheet.write_string(row, col+2, status_desc, normal_fomat)
        row += 1

    writer.close()
    output.seek(0)
    return output

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!