在openpyxl中有效地应用样式和单元格值?

时间:2020-06-12 11:37:19

标签: python openpyxl

我希望在openpyxl中找到一种更有效的编码方式/更多“ pythonic”方式来获得所需的结果。
我的迭代一次只循环遍历1个单元,而我发现它非常无效。
请帮助我改善代码!谢谢!

import openpyxl
from openpyxl.styles import Font, Border, Side

path = r"C:\Users\user\some_path"

wb = openpyxl.load_workbook(path)
sheet = wb['sheet_name']

# Apply string values and styles based on Max Rows of data entered in excel file
for i in range(1, sheet.max_row + 1):
    sheet.cell(row=i, column=1).value = 'some_string' + str(i)
    sheet.cell(row=i, column=1).font = Font(bold=True) 
    sheet.cell(row=i, column=2).border = Border(top = Side(border_style='thin', color='FF000000'), 
                                                right = Side(border_style='thin', color='FF000000'), 
                                                bottom = Side(border_style='thin', color='FF000000'), 
                                                left = Side(border_style='thin', color='FF000000'))
    sheet.cell(row=i, column=3).value = 'fixed_string'
    sheet.cell(row=i, column=3).font = Font(bold=True) 
    sheet.cell(row=i, column=4).border = Border(top = Side(border_style='thin', color='FF000000'), 
                                                right = Side(border_style='thin', color='FF000000'), 
                                                bottom = Side(border_style='thin', color='FF000000'), 
                                                left = Side(border_style='thin', color='FF000000'))

wb.save(path)

Result:
+-----------------+------------------+----------------+------------------+
|      Col1       |       Col2       |      Col3      |       Col4       |
+-----------------+------------------+----------------+------------------+
| string + str(i) | Data             | fixed string   | Data             |
| font:Bold=True  | style:All border | font:Bold=True | style:All border |
+-----------------+------------------+----------------+------------------+

0 个答案:

没有答案