我们在项目中可能用到excel表生成,下面的代码就是对excel表的操作:
1 import xlsxwriter 2 import datetime 3 4 class write_excel(): 5 def __init__(self,path): 6 now = datetime.datetime.now() 7 fname = 'TestReport' + now.strftime("%Y-%m-%d") 8 self.row = 0 9 self.xl = xlsxwriter.Workbook(path+fname+'.xlsx') 10 #print path+fname+'.xlsx' 11 12 def xls_init(self,sheetname,*titles): 13 self.sheet = self.xl.add_worksheet(sheetname) 14 self.sheet.set_column(0,len(titles)-1,20) 15 self.xls_write(*titles) 16 17 def xls_write(self,*args): 18 col = 0 19 for val in args: 20 self.sheet.write_string(self.row,col,str(val)) 21 col += 1 22 self.row += 1 23 24 def xls_close(self): 25 self.xl.close()
用法:
xlsx1 = write_excel('./test')
xlsx1.xls_init('userinfo','username','password')
xlsx1.xls_write('xiaoshitou','123456')
xlsx1.xls_close()
result: