赞
踩
Python中不同的数据类型写入Excel是不同的,比如数字,字符串,日期等。字串数字和数字写入Excel虽然显示效果一样,但是如果你想使用公式进行计算时,这个时候就会出现问题。
Excel对输入数据的不同类型(如字符串和数字)的处理方式不同
xlsxwriter中的write()方法会将Python数据类型映射到Excel支持的类型的方法
write方法可以自动的做以下方法的自动转换,可以使用write()替代以下方法:
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)
其实write()方法可以自动帮助我们完成,使用write()让代码看起来更加的简洁。
使用Demo
# -*- coding: utf-8 -*-
"""
@author:随时静听
@file: 写入其他数据类型.py
@time: 2018/08/27
@email:wang_di@topsec.com.cn
"""
#导入xlsxwriter 用于创建xlsx
import xlsxwriter
from datetime import datetime
#创建 一个Workbook 实列
book=xlsxwriter.Workbook(u'日期格式写入.xlsx')
#添加一个工作簿
sheet=book.add_worksheet()
## 以写入日期类型类例子
#创建 格式实例对象
bold=book.add_format({'bold':1}) #粗体设置
money_format=book.add_format({'num_format': '$#,##0'})
date_format=book.add_format({'num_format': 'mmmm d yyyy'})
#创建好实例后如果后期有别的需要可以通过实例来动态的修改格式,规则都是set_+key来设置
money_format.set_font_color('#2E68AA')#设置字体颜色
#通过 set_column(colum_statr,column_end,width)设置Excel表格的列宽度
sheet.set_column(1,1,20) #第二列(B)列宽设置20
#通过 set_row(row_num,height)设置Excel表格的行高
for row_ in range(20):
sheet.set_row(row_,20)#第1-20行设置行高20
#写入标题
sheet.write('A1', 'Item', bold)
sheet.write('B1', 'Date', bold)
sheet.write('C1', '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:
date = datetime.strptime(date_str, "%Y-%m-%d")#将字符串日期转成datetime实例
sheet.write_string(row, col, item)
sheet.write_datetime(row, col + 1, date, date_format)#带格式写入数据
sheet.write_number(row, col + 2, cost, money_format)#带格式写入数据
row+=1
sheet.write(row, 0, 'Total', bold)
sheet.write(row, 2, '=SUM(C2:C5)', money_format)
#关闭
book.close()
补充说明
set_column(set_range,width_value):用于设置单元格的列宽,其中set_range参数指定设置的范围,可以使用"B:E"这样格式设置
也可以使用set_column(row,col,width_value)设置,这两种的效果一样
set_row(row_num,height_value):用于设置单元格的行高,row_num指定第几行,index从0开始,表示第一行
效果展示
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。