复制单元格样式openpyxl [英] copy cell style openpyxl
本文介绍了复制单元格样式openpyxl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将工作表default_sheet
复制到同一工作簿中的新工作表new_sheet
中.
I am trying to copy a sheet, default_sheet
, into a new sheet new_sheet
in the same workbook.
我确实设法创建了一个新工作表并从默认工作表中复制了值.如何将每个单元格的样式复制到new_sheet单元格中?
I did managed to create a new sheet and to copy the values from default sheet. How can I also copy the style of each cell into the new_sheet cells?
new_sheet = workbook.create_sheet()
new_sheet.title = sheetName
default_sheet = workbook.get_sheet_by_name('default')
new_sheet = workbook.get_sheet_by_name(sheetName)
for row in default_sheet.rows:
col_idx = float(default_sheet.get_highest_column())
starting_col = chr(65 + int(col_idx))
for row in default_sheet.rows:
for cell in row:
new_sheet[cell.get_coordinate()] = cell.value
<copy also style of each cell>
我目前正在使用openpyxl 1.8.2,但是我要切换到1.8.5.
I am at the moment using openpyxl 1.8.2, but i have in mind to switch to 1.8.5.
一种解决方案是复制:
from copy import copy, deepcopy
new_sheet._styles[cell.get_coordinate()] = copy(
default_sheet._styles[cell.get_coordinate()])
推荐答案
从openpyxl 2.5.4开始,python 3.4 :(与下面的旧版本相比有细微变化)
As of openpyxl 2.5.4, python 3.4: (subtle changes over the older version below)
new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']
from copy import copy
for row in default_sheet.rows:
for cell in row:
new_cell = new_sheet.cell(row=cell.row, column=cell.col_idx,
value= cell.value)
if cell.has_style:
new_cell.font = copy(cell.font)
new_cell.border = copy(cell.border)
new_cell.fill = copy(cell.fill)
new_cell.number_format = copy(cell.number_format)
new_cell.protection = copy(cell.protection)
new_cell.alignment = copy(cell.alignment)
对于openpyxl 2.1
For openpyxl 2.1
new_sheet = workbook.create_sheet(sheetName)
default_sheet = workbook['default']
for row in default_sheet.rows:
for cell in row:
new_cell = new_sheet.cell(row=cell.row_idx,
col=cell.col_idx, value= cell.value)
if cell.has_style:
new_cell.font = cell.font
new_cell.border = cell.border
new_cell.fill = cell.fill
new_cell.number_format = cell.number_format
new_cell.protection = cell.protection
new_cell.alignment = cell.alignment
这篇关于复制单元格样式openpyxl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文