Excel 中每一个单元,都有如下属性:字体(fonts)、颜色(colors)、模式(patterns)、边界(borders)、alignment、number formatting
format = workbook.add_format() #创建自定义格式对象 (格式如下)
format.set_border(1) #设定边界宽度为1
format.set_bg_color(‘#cccccc‘) #设置背景颜色为#ccccccc
format.set_align(‘center‘) #设置对齐方式为 剧中
format.set_bold() #设置为粗体
format.set_num_format(‘0.00‘) #设置数字格式为保留两个小数
-
format = workbook.add_format()
-
-
#用对象接口设置格式属性
-
format.set_bold()
-
format.set_font_color('red')
-
-
#用字典设置格式属性
-
property = {
-
'bold': True,
-
'font_color': 'red'
-
}
-
format = workbook.add_format(property)
xlsxwriter 格式处理,将待添加数据转换成相应的格式,添加到 xlsx 文件中
-
#!/usr/bin/python
-
#coding: utf-8
-
-
from datetime import datetime
-
import xlsxwriter
-
-
workbook = xlsxwriter.Workbook('Expenses02.xlsx')
-
worksheet = workbook.add_worksheet()
-
-
#设定格式,等号左边格式名称自定义,字典中格式为指定选项
-
#bold:加粗,num_format:数字格式
-
bold_format = workbook.add_format({'bold':True})
-
money_format = workbook.add_format({'num_format':'$#,##0'})
-
date_format =workbook.add_format({'num_format':'mmmm d yyyy'})
-
-
#将二行二列设置宽度为15(从0开始)
-
worksheet.set_column(1, 1, 15)
-
-
#用符号标记位置,例如:A列1行
-
worksheet.write('A1', 'Item', bold_format)
-
worksheet.write('B1', 'Cost', bold_format)
-
worksheet.write('C1', 'Cost', bold_format)
-
-
expenses = (
-
['Rent', '2016-03-11', 1000],
-
['Gad', '2016-03-12', 100],
-
['Food', '2016-03-13', 400],
-
['Gym', '2016-03-14', 50],
-
)
-
-
row = 1
-
col = 0
-
-
for item, date_str, cost in (expenses):
-
#将数据格式转化为Python datetime.datetime 格式
-
#之后用write_datetime方法录入日期格式
-
date = datetime.strptime(date_str, "%Y-%m-%d")
-
-
#使用write_string方法,指定数据格式写入数据
-
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_format)
-
worksheet.write(row, 1, '=SUM(B2:B5)', money_format)
-
-
workbook.close()
阅读(2506) | 评论(0) | 转发(0) |