自动化之Excel操作

我们利用xlwt库进行Excel的自动化操作

实战操作演示

  1. 创建一个workbook

    wb = xlwt.Workbook()

  2. 添加一个excel sheet页

    ws = wb.add_sheet('XXX表')

  3. 定义行或列

    注意行和列都是从0开始计算的

    1
    2
    3
    4
    col_0 = ws.col(0)
    col_1 = ws.col(1)
    col_2 = ws.col(2)
    ……………………
  4. 设置列宽

    1
    2
    3
    col_0.width = 230 * 20
    col_2.width = 230 * 20
    …………
  5. 填写表头

    1
    2
    3
    ws.write(0, 0, "ID")
    ws.write(0, 1, "名称")
    ws.write(0, 2, "简介")
  6. 写入数据

    1
    2
    3
    4
    5
    dates = 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)
  7. 生成路径与文件名

    1
    2
    3
    4
    5
    6
    7
    8
    9
    now = 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 # 需要保存的文件
  8. 保存Excel文件

    1
    2
    3
    4
    5
    6
    7
    try:
    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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 <!--导出excel-->
<script type="text/javascript" src="../static/js/jquery.min.js"></script>
<script type="text/javascript">
function exportExcel() {
$.ajax({
cache: true,
type: "POST",
url: "/exportExcel",
async: false,
error: function (request) {
return false;
},
success: function (result) {
console.log(result);
window.location.href = result;
},
complete: function () {
},
error: function (data) {
layer.msg('导出失败,请重试!');
}
});
}
</script>

然后在flask中添加路由函数:

1
2
3
@app.route("/exportExcel", methods=['POST'])
def exportExcel():
pass

函数部分按上述教程编写即可

不要打赏,只求关注呀QAQ