我正在尝试为现有 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 文件的打印输出页面添加页眉/页脚,并且不更改数据。
您所做的似乎超出了您所需的结果。
您只想将标题添加到工作簿中的工作表中。无需使用 Pandas 和 Xlwriters,只需使用 Openpyxl 并更新每个工作表即可。
您的代码也有重复。如果同一代码段可用于多个应用程序,则应尽量避免重复代码。
if(textAdd == 'LGE Confidential'):
等部分不必要地重复了大约 4 行。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)