简体   繁体   English

openpyxl - 将值和 styles 从一个范围复制/粘贴到另一个范围

[英]openpyxl - copy/paste values and styles from one range to another

I'm using openpyxl to create an automated daily report.我正在使用 openpyxl 创建一个自动的每日报告。 Two questions:两个问题:

  1. Is it possible to copy values from one range to another range in one statement, eg something like,是否可以在一个语句中将值从一个范围复制到另一个范围,例如,

ws['A2':'C2'].values = ws['A1':'C1'].values

Of course this produces AttributeError: 'tuple' object has no attribute 'values' , but something along these lines.当然,这会产生AttributeError: 'tuple' object has no attribute 'values' ,但类似这些。 If not, what's the most efficient way to loop through it?如果没有,最有效的循环方式是什么?

  1. Same question but applied to cell styles.同样的问题,但适用于单元格 styles。 Is there a way to apply a named style to an entire range of cells at once?有没有办法一次将命名样式应用于整个单元格范围? If not, best way to loop it?如果没有,最好的方法是循环它?

I know there are some answers related to these questions in the Stack Overflow history, but most are dated and many use deprecated syntax.我知道在 Stack Overflow 历史中有一些与这些问题相关的答案,但大多数都已过时,并且许多使用过时的语法。

I also rely heavily with openpyxl for my daily reports.我的日常报告也非常依赖 openpyxl。

#1. #1。 I think this is one of the basic python syntax.我认为这是基本的 python 语法之一。

ws['A2'].value, ws['C2'].value = ws['A1'].value, ws['C1'].value

#2. #2。 I use loops to style a series of cells, also possible to include values.我使用循环来设置一系列单元格的样式,也可以包含值。

from openpyxl import Workbook
from openpyxl.styles import Font

wb = Workbook()
ws = wb.active

cell_reference = {
    "A1": "Date",
    "B1": "Description",
    "C1": "Debit",
    "D1": "Credit"
}

for ref, value in cell_reference.items():
    cell = ws[ref]
    cell.value = value
    cell.font = Font('Arial', bold=True)

wb.save('Sample.xlsx')
wb.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM