python_Excel_xlwt

xlwt

创建excel,向excel写入数据,并保存数据

安装

推荐方法:

通过pip 安装,方便简洁,如下图所示:

导入

import xlrd

创建workbook(即excel)

book = Workbook(encoding='utf-8')#create a workbook

创建sheet

sheet = book.add_sheet('Sheet1')#create a sheet

设置样式

#set style
font = xlwt.Font() # 字体
font.name = 'Times New Roman'
font.bold = True
font.underline = False
font.italic = False
style = xlwt.XFStyle() # 创建一个格式
style.font = font # 设置格式字体

往单元格写入

sheet.write(0, 0, "no",style)#第1行,第1列
sheet.write(0, 1, "file_name",style)#第1行,第2列
sheet.write(0, 2, "file_version",style)#第1行,第3列

保存

book.save(save_path)

 1     def writeToExcel(self):
 2         file_path = self.file_path
 3         save_path = self.save_path
 4         #write to excel
 5         print("create a workbook")
 6         book = Workbook(encoding='utf-8')#create a workbook
 7         sheet = book.add_sheet('Sheet1')#create a sheet
 8         #set style
 9         font = xlwt.Font() # 字体
10         font.name = 'Times New Roman'
11         font.bold = True
12         font.underline = False
13         font.italic = False
14         style = xlwt.XFStyle() # 创建一个格式
15         style.font = font # 设置格式字体
16         
17         #sheet.write(0, 0, label = 'Formatted value', style) # Apply the Style to the Cell
18         sheet.write(0, 0, "no",style)
19         sheet.write(0, 1, "file_name",style)
20         sheet.write(0, 2, "file_version",style)
21     
22         list = self.traverse_dir(file_path)
23         print(len(list))
24         row=0
25         num=0
26         for item in list:
27             row += 1
28             num += 1
29             print(item[0] ,item[1])
30             sheet.write(row, 0, num, style)
31             sheet.write(row, 1,item[0] , style)
32             sheet.write(row, 2,item[1] , style)
33             
34         book.save(save_path)

猜你喜欢

转载自www.cnblogs.com/yaner2018/p/9946117.html
今日推荐