如何以及其颜色和方程式一起复制Python复制Excel单元格值

2024-05-19 01:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

找了又试,到目前为止还没有找到解决办法。。。

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

上面的两个模块都无法复制保持其颜色和公式的单元格。

有没有更强大的模块来帮助我在复制单元格时保留颜色和公式?


Tags: 模块towsvalue颜色cell公式row1
3条回答

使用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

使用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

使用win32com.client可以使用Range.Copy(destination)

xlsSheet.Cells(row2, column2).Copy(xlsSheet.Cells(row1, column1))

这将复制所有内容,就像执行ctrl-c ctrl-v(值、格式等)一样。

相关问题 更多 >

    热门问题