我们利用xlwt
库进行Excel的自动化操作
实战操作演示
创建一个workbook
wb = xlwt.Workbook()
添加一个excel sheet页
ws = wb.add_sheet('XXX表')
定义行或列
注意行和列都是从0开始计算的
1
2
3
4col_0 = ws.col(0)
col_1 = ws.col(1)
col_2 = ws.col(2)
……………………设置列宽
1
2
3col_0.width = 230 * 20
col_2.width = 230 * 20
…………填写表头
1
2
3ws.write(0, 0, "ID")
ws.write(0, 1, "名称")
ws.write(0, 2, "简介")写入数据
1
2
3
4
5dates = md.get_date() # 获取数据的接口
for i,d in enumerate(dates):
ws.write(i + 1, 0, d.id)
ws.write(i + 1, 1, d.name)
ws.write(i + 1, 2, d.intro)生成路径与文件名
1
2
3
4
5
6
7
8
9now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 获取当前时间,作为文件名后缀
path = "/static/excel/" # 保存 Excel 的相对路径
fileName = "dates_" + now + ".xls" # Excel 文件名
basedir = os.path.dirname(__file__)
print("路径为" + basedir)
file_path = basedir + path # 保存 Excel 的绝对路径
if not os.path.exists(file_path): # 判断目录是否存在
os.makedirs(file_path) # 目录不存在则创建
file_path = file_path + fileName # 需要保存的文件保存Excel文件
1
2
3
4
5
6
7try:
f = open(file_path, 'r')
f.close()
except IOError:
f = open(file_path, 'w')
f.close()
wb.save(file_path)
flask导出数据到Excel
在html上添加js:
1 | <!--导出excel--> |
然后在flask中添加路由函数:
1 |
|
函数部分按上述教程编写即可