简体   繁体   中英

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

I'm using openpyxl to create an automated daily report. 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. If not, what's the most efficient way to loop through it?

  1. Same question but applied to cell 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.

I also rely heavily with openpyxl for my daily reports.

#1. I think this is one of the basic python syntax.

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

#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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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