搜索并尝试过,到目前为止尚未找到解决方案......
1。使用 openpyxl
例如:ws_to.cell(row1, column1).value = ws_from.cell(row2,column2).value
2。使用 win32com.client
例如:
xlsSheet.Cells(row1, column1).Value = xlsSheet.Cells(row2, coloum2).Value
上面的两个模块都无法复制保留其颜色和等式的单元格。
是否有更强大的模块可以帮助我在复制细胞时保持颜色和方程式?
答案 0 :(得分:1)
使用win32com.client
,您可以使用Range.Copy(destination)
:
xlsSheet.Cells(row2, column2).Copy(xlsSheet.Cells(row1, column1))
这会复制所有内容,就像你执行ctrl-c ctrl-v(值,格式化等)一样。
答案 1 :(得分:0)
使用openpyxl,您可以这样做:
# With openpyxl 1.8:
# Make sure you're loading with load_workbook('file.xlsx', data_only=False)
# Note: this behavior may be changing with openpyxl 1.9 in the future
# First, copy the value
ws_to.cell(row1, column1).value = ws_from.cell(row2,column2).value
# Second, copy the style
# Styles are stored in a table on the worksheet, you can directly copy there
# Also, set the static flag, so it knows the style is shared
# And will make a copy if you edit the style on the cell afterwards
from_style = ws_from.cell(row2,column2).style
to_coord = ws_to_cell(row1, column1).get_coordinate()
from_style.static = True # Means the style is shared, usually only set when reading a file
ws._styles[to_coord] = from_style
答案 2 :(得分:-1)
使用openpyxl 2.3.5,这成功地将一个单元格复制到另一个单元格,包括颜色/方程式:
to_cell = ws_to.cell(row1, column1)
from_cell = ws_from.cell(row2,column2)
to_cell.value = from_cell.value
to_cell.style = from_cell.style