python-写入excel(xlswriter)

一、安装XlsxWriter模块
pip install XlsxWriter
二、常用方法

import xlsxwriter
import datetime
workbook = xlsxwriter.Workbook("new_excel.xlsx")
worksheet = workbook.add_worksheet("first_sheet")
#写入文本
# 法一:
worksheet.write('A1', 'write something,this is A1')
# 法二:
worksheet.write(1, 0, 'hello A2')
# 写入数字
worksheet.write(0, 1, 32)    #B1 = 32
worksheet.write(1, 1, 32.3)  #B2 = 32.3
#写入函数
worksheet.write(2, 1, '=sum(B1:B2)')  #B3 = 64.3
# 插入图片
worksheet.insert_image(0, 5, '2.jpeg')
# worksheet.insert_image(0, 5, 'test.png', {'url': 'http://httpbin.org/'})
# 写入日期
d = workbook.add_format({'num_format': 'yyyy-mm-dd'})
worksheet.write(0, 2, datetime.datetime.strptime('2019-12-17', '%Y-%m-%d'), d)   #C1
# 设置行属性,行高设置为40
worksheet.set_row(0, 40)
# 设置列属性,把A到B列宽设置为20
worksheet.set_column('A:B', 20)
# 自定义格式
f = workbook.add_format({'border': 1, 'font_size': 13, 'bold': True, 'align': 'center','bg_color': 'cccccc'})
worksheet.write('A3', "python excel", f)
worksheet.set_row(0, 40, f)
worksheet.set_column('A:E', 20, f)
# 批量往单元格写入数据
worksheet.write_column('A15', [1, 2, 3, 4, 5])  # 列写入,从A15开始
worksheet.write_row('A12', [6, 7, 8, 9])        # 行写入,从A12开始
# 合并单元格写入
worksheet.merge_range(7,5, 11, 8, 'merge_range')
#关闭文件
workbook.close()

常用格式:
字体颜色:color
字体加粗:bold
字体大小:font_site
日期格式:num_format
超链接:url
下划线设置:underline
单元格颜色:bg_color
边框:border
对齐方式:align

你可能感兴趣的:(python-写入excel(xlswriter))