简体   繁体   中英

Openpyxl border line breaks when copying data from one sheet and then pasting it to another excel sheet

what I was trying to do using Openpyxl is that I copy some cell's values from excel sheet and then open another excel sheet and paste those values. Unexpectedly I got the sheet where the border lines broke, especially combined cells.

I'd like to hear your opinion. Also, is there a better way to loop through cells? Currently it is only three cells, but what if it is over 100.... Thank you so much.

from openpyxl import load_workbook
import os
from os.path import exists

target_file = input('ex)201711 ')
wb = load_workbook(target_file + '.xlsm', data_only=True)
sheet = wb['summary']
num_people = len(sheet['A:A'])

for i in range(1, num_people):
    val_1 = sheet.cell(row=i + 1, column=1).value
    val_2 = sheet.cell(row=i + 1, column=2).value
    val_3 = sheet.cell(row=i + 1, column=3).value

    file_name = '2017(' + val_1 + ').xlsx'
    if not exists(file_name):
        continue
    else:
        wb = load_workbook(file_name, data_only=True)
        sheet2 = wb['summary2']

        sheet2.cell(row=1, column=1).value = val_1
        sheet2.cell(row=1, column=2).value = val_2
        sheet2.cell(row=1, column=3).value = val_3
        wb.save(file_name)

I might be misunderstanding the question, but a nested for loop looks ideal...

from openpyxl import load_workbook
import os
from os.path import exists

target_file = input('ex)201711 ')
wb = load_workbook(target_file + '.xlsm', data_only=True)
sheet = wb['summary']
num_people = len(sheet['A:A'])
num_vals = 3

for i in range(1, num_people):
    for j in range(1,numvals+1):
        val[j] = sheet.cell(row=i + 1, column=j).value

    file_name = '2017(' + val[1] + ').xlsx'
    if not exists(file_name):
        continue
    else:
        wb = load_workbook(file_name, data_only=True)
        sheet2 = wb['summary2']
        for j in range(1,numvals+1):
            sheet2.cell(row=1, column=j).value = val[j]
        wb.save(file_name)

Additionally, openpyxl now supports array-index style cell referencing, which can make things easier to read/write:

#these are equivalent
sheet2.cell(row=1, column=j).value = val[j]
sheet2.[openpyxl.utils.get_column_letter(j) + '1'] = val[j]

With regards to formatting borders, in openpyxl it is (unfortunately) necessary to explicitly specify all borders on merged cells, unlike the default excel action where the styling of the topleft cell is applied over the merge.

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