提问人:Thảo Nguyễn 提问时间:11/14/2023 最后编辑:mokenThảo Nguyễn 更新时间:11/15/2023 访问量:55
蟒;在不更改数据的情况下为现有 Excel 文件上的打印页面添加页眉/页脚
Python; Add header/footer for printout page(s) on existing Excel file without changing data
问:
我正在尝试为现有 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 文件的打印页面添加页眉/页脚,并且不更改数据。
答:
1赞
moken
11/15/2023
#1
您似乎做得比所需结果所需的更多。
您只想将标题添加到工作簿中的工作表中。无需为此使用 Pandas 和 Xlwriters,只需使用 Openpyxl 并更新每个工作表即可。
此外,您的代码中有重复代码,如果同一代码段可用于多个应用程序,请尽量避免重复代码。该部分等不必要地重复了大约 4 行。
使用 Openpyxl,您可以将页眉(和页脚)设置为左、中、右三个部分之一,并允许对第一页和奇数/偶数页进行不同的设置。在示例中,我使用了“中心”部分并包含所有页面,因此您可以更改为适合的页面。
据我所知,对于您想要的内容,以下代码示例应该可以满足您的需求。我已经硬设置了“textAdd”字符串,以便代码可以运行,在每条代码之间更改以进行测试。if(textAdd == 'LGE Confidential'):
import openpyxl
import glob
import os
def addExcelFile(textAdd, workbook):
### 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 workbook.worksheets:
sheet.firstHeader.center.text = headertext
sheet.oddHeader.center.text = headertext
sheet.evenHeader.center.text = headertext
locationPath = '<path>'
### Header text (textAdd). Hard set here for code runability
ta = 'LGE Confidential'
# ta = 'LGE Internal Use Only'
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)
### Call function to add Header to workbook sheets
addExcelFile(ta, wb)
### Save updated workbook
wb.save(file)
评论
0赞
Thảo Nguyễn
11/21/2023
非常感谢您的指导。我会试试的
评论