一、
xlsxwriter速度快,但不能读
而openpyxl可以读和写
二、Example
import xlsxwriter
#创建一个新表
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
#扩大第一列的宽度
worksheet.set_column('A:A', 20)
#添加一个bold格式强调单元格
bold = workbook.add_format({'bold': True})
#写一些简单的文本
worksheet.write('A1', 'Hello')
#带有格式的写入
worksheet.write('A2', 'World', bold)
#写一些数字通过行列
worksheet.write(2, 0, 123)
worksheet.write(3, 0, 123.456)
#插入一张图片
#worksheet.insert_image('B5', 'logo.png')
#关闭
workbook.close()
三、深入一小步
(一)
import xlsxwriter
#创建一个新表
workbook = xlsxwriter.Workbook('Expenses01.xlsx')
worksheet = workbook.add_worksheet()
#一些我们想写进表里的数据
expenses = (
['Rent', 1000],
['Gas', 100],
['Food
', 300],
['Gym', 50],
)
#从第一单元开始,行和列是零索引
row = 0
col = 0
#迭代这些数据并一行行写入
for item, cost in (expenses):
worksheet.write(row, col, item)
worksheet.write(row, col + 1, cost)
row += 1
#用算式写入合计
worksheet.write(row, 0, 'Total')
worksheet.write(row, 1, '=SUM(B1:B4)')
workbook.close()
(二)
import xlsxwriter
#创建一个新表
workbook = xlsxwriter.Workbook('Expenses02.xlsx')
worksheet = workbook.add_worksheet()
#添加一个粗体格式使用强调单元格
bold = workbook.add_format({'bold': True})
#添加一个使用于money数据格式的数字格式
money = workbook.add_format({'num_format': '$#,##0'})
#写一些数据作为标题
worksheet.write('A1', 'Item', bold)
worksheet.write('B1', 'Cost', bold)
#一些我们想写进表里的数据
expenses = (
['Rent', 1000],
['Gas', 100],
['Food', 300],
['Gym', 50],
)
#从第一行的标题下开始,行和列是零索引
row = 1
col = 0
#迭代这些数据并一行行写入
for item, cost in (expenses):
worksheet.write(row, col, item)
worksheet.write(row, col + 1, cost, money)
row += 1
#用算式写入合计
worksheet.write(row, 0, 'Total', bold)
worksheet.write(row, 1, '=SUM(B2:B5)', money)
workbook.close()
(三)
import xlsxwriter
from datetime import datetime
#创建一个新表
workbook = xlsxwriter.Workbook('Expenses03.xlsx')
worksheet = workbook.add_worksheet()
#添加一个粗体格式使用强调单元格
bold = workbook.add_format({'bold': True})
#添加一个使用于money数据格式的数字格式
money_format = workbook.add_format({'num_format': '$#,##0'})
#使用一个excel日期格式
date_format = workbook.add_format({'num_format': 'mmmm d yyyy'})
#调整列宽度
worksheet.set_column(1, 1, 20)
#写一些数据作为标题
worksheet.write('A1', 'Item', bold)
worksheet.write('B1', 'Cost', bold)
#一些我们想写进表里的数据
expenses = (
['Rent', '2013-01-13', 1000],
['Gas', '2013-01-14', 100],
['Food', '2013-01-16', 300],
['Gym', '2013-01-20', 50],
)
#从第一行的标题下开始,行和列是零索引
row = 1
col = 0
#迭代这些数据并一行行写入
for item, date_str, cost in (expenses):
#把日期的字符串转化为datetime对象
date = datetime.strptime(date_str, "%Y-%m-%d")
worksheet.write_string (row, col, item )
worksheet.write_datetime(row, col + 1, date, date_format )
worksheet.write_number (row, col + 2, cost, money_format)
row += 1
#用算式写入合计
worksheet.write(row, 0, 'Total', bold)
worksheet.write(row, 2, '=SUM(C2:C5)', money_format)
workbook.close()