介绍
XlsxWriter是一个Python模块,用于以Excel 2007+ XLSX文件格式编写文件。
它可以用于将文本,数字和公式写入多个工作表,并且支持诸如格式设置,图像,图表,页面设置,自动过滤器,条件格式设置等功能。
但是 XlsxWriter只能创建新文件。它无法读取或修改现有文件。
安装XlsxWriter
pip install XlsxWriter
创建XLSX文件
import xlsxwriter
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()
# Some data we want to write to the worksheet.
expenses = (
['Rent', 1000],
['Gas', 100],
['Food', 300],
['Gym', 50],
)
# Start from the first cell. Rows and columns are zero indexed.
row = 0
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)
row += 1
# Write a total using a formula.
worksheet.write(row, 0, 'Total')
worksheet.write(row, 1, '=SUM(B1:B4)')
workbook.close()
将获得一个如下所示的电子表格:
- Workbook 接受一个非可选参数,即我们要创建的文件名:
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
- add_worksheet()方法使用工作簿对象添加新的工作表 :
worksheet2 = workbook.add_worksheet('Data') # 名为Data工作表.
- write()方法写入数据:
worksheet.write(row, col, some_data)
- close()方法关闭Excel文件:
workbook.close()
将格式添加到XLSX文件
1. 使用对象接口
# Add a bold format to use to highlight cells.
cell_format = workbook.add_format()
cell_format.set_bold()
cell_format.set_font_color('red')
# Write some data headers.
worksheet.write('A1', 'Item', cell_format)
2. 将属性设置为构造函数中键/值对的字典
# Add a bold format to use to highlight cells.
cell_format = workbook.add_format({'bold': True, 'font_color': 'red'})
# Write some data headers.
worksheet.write('A1', 'Item', cell_format)
需要注意的是:
XlsxWriter电子表格中的每种唯一单元格格式都必须具有一个对应的Format对象。不能将Format与write()
方法一起使用,然后重新定义它以供以后使用。这是因为格式不是以当前状态而是以最终状态应用于单元格。考虑以下示例:
cell_format = workbook.add_format({'bold': True, 'font_color': 'red'})
worksheet.write('A1', 'Cell A1', cell_format)
# Later...
cell_format.set_font_color('green')
worksheet.write('B1', 'Cell B1', cell_format)
单元格A1分配了一种格式,该格式最初将字体设置为红色。但是,颜色随后设置为绿色。当Excel显示单元格A1时,它将显示格式的最终状态,在这种情况下将为绿色。
将不同类型的数据写入XLSX文件
Excel通常以不同的方式对用户透明地处理不同类型的输入数据,例如字符串和数字。XlsxWriter尝试在工作表中对此进行模拟。write()通过将Python数据类型映射到Excel支持的类型的方法。
- write_string()
- write_number()
- write_blank()
- write_formula()
- write_datetime()
- write_boolean()
- write_url()
worksheet.write_string (row, col, item )
worksheet.write_datetime(row, col + 1, date, date_format )
worksheet.write_number (row, col + 2, cost, money_format)
爬虫中的数据存储
def save_to_xlsx(filename, data):
# data = [ {'key1': 'value1', 'key2', 'value2'}, {}, {}]
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
bg_format = workbook.add_format()
bg_format.set_pattern(1)
# 写入头
fieldnames = data[0].keys()
for col, fieldname in enumerate(fieldnames):
worksheet.write(0, col, fieldname)
for row, items in enumerate(data):
real_row = row + 1
for col, (key, value) in enumerate(items.items()):
worksheet.write_string(real_row, col, value)
workbook.close()
参考
XlsxWriter