社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python和openpyxl-在新文件中“追加”一行时,如何复制样式?

RisoGalloExresso • 3 年前 • 2391 次点击  

在我的代码下面:

import openpyxl

# file 1:
path = "C:\\Users\\Admin\\Desktop\\TEST.xlsx"
wb_1 = openpyxl.load_workbook(path, read_only=True)
ws_1 = wb_1[wb_1.sheetnames[0]]

# file 2 (it's a new file):
wb_2 = openpyxl.Workbook()
ws_2 = wb_2.active
ws_2.title = "SHEET"

# copy the rows placed in file 1 into the file 2:
def GetList(row):
    list_for_row_values = []
    for cell in row:
        list_for_row_values.append(cell.value)
    return list_for_row_values

for row in ws_1.rows:
    list_for_row_values = GetList(row)
    ws_2.append(list_for_row_values)

wb_2.save("C:\\Users\\Admin\\Desktop\\result.xlsx")

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/99356
 
2391 次点击  
文章 [ 2 ]  |  最新文章 3 年前
ShinNShirley
Reply   •   1 楼
ShinNShirley    3 年前

为什么必须使用函数 append ?

如:

import openpyxl,os
from copy import copy

path = '1.xlsx'
wb_1 = openpyxl.load_workbook(path)
ws_1 = wb_1[wb_1.sheetnames[0]]
wb_2 = openpyxl.Workbook()
ws_2 = wb_2.active
ws_2.title = "SHEET"
ws_2.sheet_format = ws_1.sheet_format

for (row, col), source_cell  in ws_1._cells.items():
    cell = ws_2.cell(column=col, row=row)
    cell.value = source_cell.value
    cell.font = copy(source_cell.font)
    cell.fill = copy(source_cell.fill)
    cell._hyperlink = source_cell._hyperlink
    cell.comment = source_cell.comment
wb_2.save('11.xlsx')
eNc
Reply   •   2 楼
eNc    3 年前

我在这里提出的解决方案是一种适应 from this post openpyxl documentation

我的输入xlsx如下所示:

enter image description here

代码如下:

import openpyxl

# file 1:
wb_1 = openpyxl.load_workbook(in_path, read_only=True)
ws_1 = wb_1[wb_1.sheetnames[0]]

# file 2 (it's a new file):
wb_2 = openpyxl.Workbook()
ws_2 = wb_2.active

for r in ws_1.rows:
    for c in r:
        ws_2.cell(row=c.row, column=c.column).value = c.value
        ws_2.cell(row=c.row, column=c.column).fill = c.fill
        ws_2.cell(row=c.row, column=c.column).font = c.font
        ws_2.cell(row=c.row, column=c.column).number_format = c.number_format
        ws_2.cell(row=c.row, column=c.column).border = c.border

wb_2.save(out_path)

这是我的输出文档:

enter image description here

基本上,我的内部循环是代码的副本:

    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)

所以他的部分功劳归于@CharlieClark (link is here again)

如果你想让别人回答你的问题,至少试着使用他们在评论中提供的信息。尤其是如果您是python或某个特定包的新手。这不是一个编程服务,你至少应该试着找出一个解决方案,然后再声称你的帖子不是重复的或者问题还没有得到回答。