3、Python文件操作工具 xlwt 工具

# _*_ encoding:utf-8 _*_

import xlrd
import xlwt

#新建excel文件
excel = xlwt.Workbook(encoding='utf-8')
#添加sheet页,并命名
sheet1 = excel.add_sheet('肉食类',cell_overwrite_ok=True)
# 使用style
# 初始化样式
style = xlwt.XFStyle()

# 为样式创建字体
font = xlwt.Font()
font.name = 'Times New Roman'
font.bold = True

# 为样式设置字体
style.font = font
number = [1,2,3,4]
dishes = [u'黄瓜炒肉',u'苦瓜炒肉',u'西蓝花炒肉',u'辣椒炒肉']
price = [12,34,21,33]

#添加文档title行
sheet1.write(0,0,u'编号',style=style)
sheet1.write(0,1,u'菜名',style=style)
sheet1.write(0,2,u'价格',style=style)

#向文档中写入数据
for row in range(1,5):
for col in range(0,3):
if col == 0:
sheet1.write(row,col,number[row-1])
if col == 1:
sheet1.write(row, col, dishes[row - 1])
if col == 2:
sheet1.write(row, col, price[row - 1])

#保存数据
excel.save(r'..file_practice.xls')



#xlwt 允许单元格或者整行地设置格式。还可以添加链接以及公式。可以阅读源代码,那里有例子:

#dates.py, 展示如何设置不同的数据格式

#hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)

#merged.py, 展示如何合并格子

#row_styles.py, 展示如何应用Style到整行格子中.


原文地址:https://www.cnblogs.com/cindy-cindy/p/7910757.html