[英]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. 我尝试使用Openpyxl进行的操作是,我从excel工作表中复制了一些单元格的值,然后打开另一个excel工作表并粘贴了这些值。 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. 当前只有三个单元,但是如果超过100个,该怎么办。...非常感谢。
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... 我可能会误解这个问题,但是嵌套的for循环看起来很理想...
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: 此外,openpyxl现在支持数组索引样式的单元格引用,这可以使事情更易于读取/编写:
#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. 关于设置边框格式,在openpyxl中(不幸地)有必要显式指定合并单元格上的所有边框,这与默认的excel操作不同,默认的excel操作将左上单元格的样式应用于合并。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.