使用openpyxl在Python中将工作表(数据+样式)从一个工作簿复制到另一个工作簿



我有大量的XLS文件(超过500个(,我只需要替换第一张纸。需要是第一个工作表的数据+样式(字体、背景、边框、单元格对齐方式甚至图像(的完美副本。

我在Python中发现的所有使用openpyxl的解决方案都只允许它复制数据,而不允许它复制样式。使用xlwings不是一个选项,因为Linux目标机器没有MS Office。

import openpyxl as pyxl
import re
basereportworkbook = pyxl.load_workbook(filename="base_template.xlsx")
testreportworkbook = pyxl.load_workbook(filename="file1_to_correct.xlsx")
sheetbase = basereportworkbook.get_sheet_by_name("Coverpage")
sheetreport = basereportworkbook.get_sheet_by_name("Coverpage")
# Remove the 1st page from the file to correct
testreportworkbook.remove(testreportworkbook["Coverpage"])
testreportworkbook.create_sheet("Coverpage")
sheetreport = testreportworkbook.get_sheet_by_name("Coverpage")

# Copying the cell values from template excel file to destination excel file, one by one
mr = sheetbase.max_row 
mc = sheetbase.max_column 
for i in range (1, mr + 1): 
for j in range (1, mc + 1): 
# reading cell value from source excel file 
c = sheetbase.cell(row = i, column = j) 

# writing the read value to destination excel file 
sheetreport.cell(row = i, column = j).value = c.value 
# Save the XLS file in the disk
testreportworkbook.save(filename="output.xlsx")

到目前为止,这是我的代码,它只适用于复制没有格式样式的数据。谢谢

使用c.value时,指定只复制值,而不复制任何其他单元格属性(格式等(。您可以使用copy移动所有_style格式,例如:

from copy import copy
sheetreport.cell(row = i, column = j).value = c.value
if cell.has_style:
sheetreport.cell(row = i, column = j)._style = copy(c._style)

但是,如果你只想复制整个工作表,我可能只复制整个工作簿,然后删除所有其他工作表,而不是遍历每个单元格。

shutil.copyfile('base_template.xlsx', 'file1_to_correct.xlsx')
testreportworkbook = pyxl.load_workbook(filename='file1_to_correct.xlsx')
for ws in testreportworkbook.worksheets[1:]:
testreportworkbook.remove_sheet(ws)

还要注意,从文档中:;您也不能在工作簿之间复制工作表。如果工作簿以只读或只读模式打开,则无法复制工作表">

相关内容

最新更新