我想用openpyxl快速读写我的excel文件

时间:2019-11-07 09:40:54

标签: python excel openpyxl

我的代码很慢 我想让速度更快 例如: 该代码应采用a1单元格中的值并更改其值,然后在同一单元格中再次重写 你能帮我吗?

import openpyxl

row = 1
counter = 0
while row <= 20980:
    book = openpyxl.load_workbook('semsar_full.xlsx')
    sheet = book.active
    a3 = sheet.cell(row=row, column=1)
    a4 = a3.value + ':::'
    sheet.cell(row=row, column=1, value=a4)
    counter += 1
    row += 1
    print(counter)
    book.save('semsar_full.xlsx')

1 个答案:

答案 0 :(得分:1)

我认为速度很慢时最大的问题是您正在加载+保存包含的每一行的文件。如果将load + save置于循环之外,则代码应该会更快。

import openpyxl

book = openpyxl.load_workbook('semsar_full.xlsx')
sheet = book.active
row = 1
counter = 0
while row <= 20980:

    a3 = sheet.cell(row=row, column=1)
    a4 = a3.value + ':::'
    sheet.cell(row=row, column=1, value=a4)
    counter += 1
    row += 1
    print(counter)

book.save('semsar_full.xlsx')