Python;在现有 Excel 文件上添加打印输出页面的页眉/页脚,而不更改数据

问题描述 投票:0回答:1

我正在尝试为现有 Excel 文件的所有工作表添加打印标题标题。
我编写了如下所示的代码,但它创建了新工作表并且所有数据都将丢失。

如何为现有 Excel 文件的打印输出页面添加页眉/页脚而不更改数据?

import xlsxwriter
import pandas as pd
import glob
import os

def addExcelFile(locationPath, textAdd):
    
    for file in glob.glob(locationPath + '\\**\\*.xlsx', recursive=True):        
        errorFile = os.path.basename(file).split('/')[-1]
        print(errorFile[0:2])
        if (errorFile[0:2] != '~$'):
            print(file)
            xl = pd.ExcelFile(file, engine='openpyxl')

            # Open a Pandas Excel writer using XlsxWriter as the engine.
            writer = pd.ExcelWriter(file, engine='xlsxwriter')
            # Get the xlsxwriter workbook and worksheet objects.
            workbook  = writer.book
            listSheet = xl.sheet_names
            print(len(listSheet))
            # see all sheet names
            if(textAdd == 'LGE Confidential'):
                for i in range (0,len(listSheet)):
                    nameSheet = listSheet[i]
                    writer.sheets={nameSheet:workbook.add_worksheet()}
                    worksheet = writer.sheets[nameSheet]
                    # Set color for text :https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.colors?view=windowsdesktop-7.0 
                    # replace char FF -> K in start color code 
                    worksheet.set_header('&C&"Tahoma,Bold"&14&Kff0000' + textAdd)

            elif(textAdd == 'LGE Internal Use Only'):
                for i in range (0,len(listSheet)):
                    nameSheet = listSheet[i]
                    writer.sheets={nameSheet:workbook.add_worksheet()}
                    worksheet = writer.sheets[nameSheet]
                    # Set color for text :https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.colors?view=windowsdesktop-7.0 
                    # replace char FF -> K in start color code 
                    worksheet.set_header('&C&"Tahoma,Bold"&14&Ka9a9a9' + textAdd)

            # Close the Pandas Excel writer and output the Excel file.
            writer.save()
            xl.close()
        else:
            print('File error: ', file, '. It will not be add header!')

为现有 Excel 文件的打印输出页面添加页眉/页脚,并且不更改数据。

python excel header openpyxl
1个回答
0
投票

您所做的似乎超出了您所需的结果。
您只想将标题添加到工作簿中的工作表中。无需使用 Pandas 和 Xlwriters,只需使用 Openpyxl 并更新每个工作表即可。
您的代码也有重复。如果同一代码段可用于多个应用程序,则应尽量避免重复代码。

if(textAdd == 'LGE Confidential'):
等部分不必要地重复了大约 4 行。
Openpyxl 将页眉(和页脚)设置为左、中、右三个部分之一,并允许对第一页和奇数/偶数页进行不同的设置。在示例中,我使用了“center”并包含了所有内容,以便您可以更改为适合的内容。

据我所知,以下代码示例应该可以满足您的需要。

import openpyxl
import glob
import os


def addExcelFile(locationPath, textAdd):
    for file in glob.glob(locationPath + '\\**\\*.xlsx', recursive=True):
        errorFile = os.path.basename(file).split('/')[-1]
        print(errorFile[0:2])
        if errorFile[0:2] != '~$':
            print(file)
    
            ### Open the workbook with Openpyxl
            wb = openpyxl.load_workbook(file)

            ### Set the colour for the header, only two variations based on the text. Grey can be the 
            ### default colour which is set and only changed if the text is 'LGE Confidential'
            head_color = 'a9a9a9'  # Default to Grey
            if textAdd == 'LGE Confidential':  
                head_color = 'ff0000'  # Change to red if the text is 'LGE Confidential'

            ### Create the Header from the default style, colour and text
            headertext = '&C&"Tahoma,Bold"&14&K' + head_color + textAdd

            ### Add the header as needed 
            for sheet in wb.worksheets:
                sheet.firstHeader.center.text = headertext
                sheet.oddHeader.center.text = headertext
                sheet.evenHeader.center.text = headertext

            wb.save(file)


© www.soinside.com 2019 - 2024. All rights reserved.