我们在项目中可能用到excel表生成,下面的代码就是对excel表的操作:
import xlsxwriter
import datetime class write_excel():
def __init__(self,path):
now = datetime.datetime.now()
fname = 'TestReport' + now.strftime("%Y-%m-%d")
self.row = 0
self.xl = xlsxwriter.Workbook(path+fname+'.xlsx')
#print path+fname+'.xlsx' def xls_init(self,sheetname,*titles):
self.sheet = self.xl.add_worksheet(sheetname)
self.sheet.set_column(0,len(titles)-1,20)
self.xls_write(*titles) def xls_write(self,*args):
col = 0
for val in args:
self.sheet.write_string(self.row,col,str(val))
col += 1
self.row += 1 def xls_close(self):
self.xl.close()
用法:
xlsx1 = write_excel('./test')
xlsx1.xls_init('userinfo','username','password')
xlsx1.xls_write('xiaoshitou','123456')
xlsx1.xls_close()
result: