我正在使用Excel,我必须将一些列导出到另一个列,但这第二个是一个模板,有一些 colored颜色 ,公司的徽标和东西. 有没有办法保留template.xlsx的外观和功能?

My code:

import pandas as pd

#variables for source file, worksheets, and empty dictionary for dataframes
spreadsheet_file = pd.ExcelFile('example.xlsx')
worksheets = spreadsheet_file.sheet_names

appended_data = {}
cat_dic = {"Part Number":"CÓDIGO", "QTY":"QT", "Description":"DESCRIÇÃO", "Material":"MATERIAL", "Company":"MARCA","Category":"OPERAÇÃO"}
d = {}

for sheet_name in worksheets:
  df = pd.read_excel(spreadsheet_file, sheet_name)
  #Getting only the columns asked: "Part Number","QTY","Description","Material","Company","Category"
  df = df[["Part Number","QTY","Description","Material","Company","Category"]]
  #Organizing info:
  #1º By Category
  #2º By Description
  df = df.sort_values(['Category', 'Description'], ascending = [False, False])
  appended_data = df.to_dict()
  #Change Key names
  d = dict((cat_dic[key], value) for (key, value) in appended_data.items())
  #Exporting Data
  df2 = pd.DataFrame(d)
  df2.to_excel('template2.xlsx',sheet_name='Projeto',index=False)

Example:

enter image description here

Template:

enter image description here

My output:

enter image description here

事先感谢您的帮助.

推荐答案

如果您只想更新文本并保持模板中的格式、 colored颜色 等不变,则需要使用Openpyxl.更新了下面的代码.请注意

  • 我没有使用您的df2代码,因为模板文件已经有了新的头文件.仅将每个工作表中的数据更新到文件中
  • 您可以使用READ_EXCEL读取每个工作表,但需要使用Openpyxl.Load_Workbook进行写入,最后在读取所有工作表后保存文件
  • 在for循环之前使用LOAD_WORKBOOK打开上图中所示的模板文件,并在for循环完成后保存到新文件template2
spreadsheet_file = pd.ExcelFile('example.xlsx')
worksheets = spreadsheet_file.sheet_names
#cat_dic = {"Part Number":"CÓDIGO", "QTY":"QT", "Description":"DESCRIÇÃO", "Material":"MATERIAL", "Company":"MARCA","Category":"OPERAÇÃO"}
#d = {}

import openpyxl
from openpyxl.utils.dataframe import dataframe_to_rows
wb=openpyxl.load_workbook('Template.xlsx')  ##Your Template file
ws=wb['Sheet1']
rownumber=2 ##Skip 2 rows and start writing from row 3 - first two are headers in template file

for sheet_name in worksheets:
    df = pd.read_excel(spreadsheet_file, sheet_name)
    #Getting only the columns asked: "Part Number","QTY","Description","Material","Company","Category"
    df = df[["Part Number","QTY","Description","Material","Company","Category"]]
    #Organizing info:
    #1º By Category
    #2º By Description
    df = df.sort_values(['Category', 'Description'], ascending = [False, False])

    rows = dataframe_to_rows(df, index=False, header=False) ## Read all rows from df, but don't read index or header
    for r_idx, row in enumerate(rows, 1):
        for c_idx, value in enumerate(row, 1):
             ws.cell(row=r_idx+rownumber, column=c_idx, value=value) Write to cell, but after rownumber + row index
            
    rownumber += len(df) ##Move the rownumber to end, so next worksheet data comes after this sheet's data 

wb.save('template2.xlsx')

Python相关问答推荐

根据二元组列表在pandas中创建新列

如何在Django基于类的视图中有效地使用UTE和RST HTIP方法?

如何在Raspberry Pi上检测USB并使用Python访问它?

不允许访问非IPM文件夹

将pandas导出到CSV数据,但在此之前,将日期按最小到最大排序

matplotlib + python foor loop

Tensorflow tokenizer问题.num_words到底做了什么?

如何使用matplotlib查看并列直方图

简单 torch 模型测试:ModuleNotFoundError:没有名为';Ultralytics.yolo';

为罕见情况下的回退None值键入

Django在一个不是ForeignKey的字段上加入'

Seaborn散点图使用多个不同的标记而不是点

用来自另一个数据框的列特定标量划分Polars数据框中的每一列,

删除Dataframe中的第一个空白行并重新索引列

Pythonquests.get(Url)返回Colab中的空内容

为什么我的scipy.optimize.minimize(method=";newton-cg";)函数停留在局部最大值上?

如何使用Polars从AWS S3读取镶木地板文件

利用广播使减法更有效率

Pandas 数据框自定义排序功能

如何在保持sibling 姐妹美汤的同时插入和删除标签?