简体   繁体   中英

Python Openpyxl - Copy values from column A to B with same rows range

I'm iterating through the column A. Inside this column I'm using two functions to unicode values.

# -*- coding: utf-8 -*-

from django.template import defaultfilters
from unidecode import unidecode
import openpyxl

wb = openpyxl.load_workbook('sheet.xlsx', use_iterators=True)
sheet = wb.get_sheet_by_name('Sheet1')

translated = []

for row in sheet.iter_rows('A2:A74'):
   for cell in row:
       if cell.value is not None:
           defaultfilters.slugify(unidecode(cell.value))
           translated.append(defaultfilters.slugify(unidecode(cell.value)))

It all works so far, but now I'd like to paste these "converted" values to column B with the same range B2-B74. Has anyone would help me with this code to solve my problem ? I was "googling" but I didn't find solution so far...

Have you tried doing it in a similar way to way you read them?

Edit, couple of fixes:

Edit2, minor improvements (I had some tautological logic):

ie:

import openpyxl

wb = openpyxl.load_workbook('sheet.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

translated = []
for row in sheet.iter_rows('A2:A74'):
    for cell in row:
        translated.append(cell.value)

for row, val in zip(sheet.iter_rows('B2:B74'), translated):
    for cell in row:
        cell.value = val

wb.save("sheet.xlsx")

So, very similar to how you access the cells, and then you need to save the workbook at the end! Does this work for you? Previously you were opening the workbook in read only mode.

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