有没有办法模仿“Excel”或“LibreOffice Calc”的复制功能
openpyxl
还有蟒蛇3号?
我想指定某个范围(例如“A1:E5”)并复制“边框”、“对齐”、“数字\u格式”、“值”、“合并的\u单元格”、。。。将每个单元格的属性设置到其他位置(可能是另一个工作表),由此使用的公式应自动更新到新位置。新公式旨在引用目标工作表中的单元格,而不是原始工作表中的旧单元格。
我的项目:
我每月生成一份工作簿。此工作簿包含列出所有工作日的产量监控表。
虽然每个月的表格都不同,但工作簿中的所有表格都具有相同的结构,因此我想创建一个模板并将其粘贴到各个工作表中。
复制整个工作表并不是真正的解决方案,因为我还喜欢为每个工作表分别指定表的位置。因此,目标工作表中的位置可能与模板中的位置不同。
我的当前代码(公式不会自动更新):
import copy
# The tuple "topLeftCell" represents the assumed new position in the target worksheet. It is zero-based. (e.g. (0,0) or (7,3))
# "templateSheet" is the template from which to copy.
# "worksheet" is the target worksheet
# Create the same "merged_cells" as in the template at the new positioin
for cell_range in templateSheet.merged_cells.ranges:
startCol, startRow, endCol, endRow = cell_range.bounds
worksheet.merge_cells(start_column=topLeftCell[0] + startCol,
start_row=topLeftCell[1] + startRow,
end_column=topLeftCell[0] + endCol,
end_row=topLeftCell[1] + endRow)
colNumber = topLeftCell[0] + 1 # 1 is added up because topLeftCell is zero based.
rowNumber = topLeftCell[1] + 1 # 1 is added up because topLeftcell is zero based.
# Copy the properties of the old cells into the target worksheet
for row in templateSheet[templateSheet.dimensions]:
tmpCol = colNumber # sets the column back to the original value
for cell in row:
ws_cell = worksheet.cell(column=tmpCol, row=rowNumber)
ws_cell.alignment = copy.copy(cell.alignment)
ws_cell.border = copy.copy(cell.border)
ws_cell.font = copy.copy(cell.font)
ws_cell.number_format = copy.copy(cell.number_format)
ws_cell.value = cell.value
tmpCol += 1 # move one column further
rowNumber += 1 # moves to the next line
由于复制范围实际上是一项常见的任务,我假设openpyxl提供了一个函数或方法。不幸的是,我到目前为止还没有找到。
我使用的是openpyxl版本2.5.1(和Python 3.5.2)。
顺致敬意,
AFOEE公司