1.新增表并添加数据;
2.给工作表添加表名称,给表数据添加格式;
import xlsxwriter
datas=(['Rent',1000],
['Gas',100],
['fish','画画'],
['rice',500])
a=xlsxwriter.Workbook('st.xlsx')
sh1=a.add_worksheet('表1') #添加工作表名称
money=a.add_format({'num_format':"$#,##0"}) #添加数字格式
bold=a.add_format({'bold':True}) #加粗
#添加表头,并加粗
sh1.write('A1','Item',bold)
sh1.write(0,1,'Cost',bold)
r,c=1,0
for names,costs in datas:
sh1.write(r,c,names)
sh1.write(r,c+1,costs,money) #给列添加数字格式
r+=1
sh1.write(r,c,'total',bold)
sh1.write(r,c+1,'=sum($B2:B5)',money)
a.close()
3.excel表中添加不同类型数据;
import xlsxwriter
from datetime import datetime
datas=(['huahua','2019-2-3',20],
['huamei','2009-7-8',40],
['港币','1998-1-2',3470]) a=xlsxwriter.Workbook('info.xlsx') #创建excel表
sh1=a.add_worksheet('人员信息表') #创建工作表
bold=a.add_format({"bold":True}) #添加加粗格式
money=a.add_format({"num_format":"$#,##0"})
date=a.add_format({"num_format":"mmmm d yyyy"})
sh1.write(0,0,'name',bold)
sh1.write('B1','birthd',bold)
sh1.write('C1','age',bold)
row,column=1,0
for name,birthd,salary in datas:
birthd=datetime.strptime(birthd,'%Y-%m-%d')
sh1.write(row,column,name)
sh1.write(row,column+1,birthd,date)
sh1.write(row,column+2,salary,money)
row+=1
sh1.write(row,column+1,'total_m',bold)
sh1.write(row,column+2,'=sum(B2:B4)',money)
a.close()