使用Python 处理 excel 速成课(openpyxl 实现)Note 3
本课时主要是一些 openpyxl 对 excel 的数字格式,Excel 函数公式
数字格式
(1) excel 里对python里数字和文本的显示
# 导入包,并获取一个工作表用以展示
import openpyxl
wb = openpyxl.Workbook()
ws = wb.active
# 导入演示数据
ws.append(['文本', '数字'])
ws['A2'] = '520' # python 里的字符串
ws['B2'] = 520 # python 里的数字
wb.save('demo3.xlsx')
(2)python里的文本在excel里会按原样显示,但是数字在excel里有很多种类,如图:
在openpyxl 里有一些内置的字符格式,当然我们也可以自定义一些字符格式如下面的例子:
(detail 在openpyxl 官方文档:https://openpyxl.readthedocs.io/en/latest/styles.html#using-number-formats )
import datetime
ws['C1'] = 1314
ws['C1'].number_format = '#,###.00 元'
ws['C2'] = datetime.datetime.today()
ws['C2'].number_format = 'yyyy-mm-dd'
ws['C3'] = 13
ws['C3'].number_format = '####'
ws['C4'] = 13
ws['C4'].number_format = '0000'
wb.save(