Configuración de encabezados y pies de página

Configuración de encabezados y pies de página

Aspose.Cells para Python via .NET permite agregar encabezados y pies de página a las hojas de trabajo en tiempo de ejecución, pero se recomienda configurar los encabezados y pies de página manualmente en un archivo pre-diseñado para impresión. Puedes usar Microsoft Excel como una herramienta GUI para establecer encabezados y pies de página y ahorrar esfuerzo y tiempo de desarrollo. Aspose.Cells para Python via .NET puede importar el archivo y guardar la configuración.

Para agregar encabezados y pies de página en tiempo de ejecución, Aspose.Cells para Python via .NET proporciona llamadas API especiales y comandos de script para formatear encabezados y pies de página.

Comandos de Script

Los comandos de script son comandos especiales que le permiten configurar el formato de los encabezados y pies de página.

Comandos de Script Descripción
&P Número de página actual
&G Una imagen
&N El número total de páginas
&D La fecha actual
&T La hora actual
&A Nombre de la hoja de cálculo
&F El nombre del archivo sin su ruta
&"<FontName>" Representa un nombre de fuente. Por ejemplo: &“Arial”
&"<FontName>, <FontStyle>" Representa el nombre de la fuente con estilo. Por ejemplo: &“Arial,Negrita”
&<FontSize> Representa el tamaño de la fuente. Por ejemplo: “&14abc”. Sin embargo, si este comando va seguido de un número normal a imprimir en el encabezado, esto debe separarse con un carácter de espacio del tamaño de la fuente. Por ejemplo: “&14 123”.

Cómo Establecer Encabezados y Pies de Página

La clase PageSetup proporciona dos métodos, set_header y set_footer, utilizados para agregar un encabezado y un pie de página a una hoja de trabajo. Estos métodos solo toman dos parámetros:

  • Sección – la sección donde se debe colocar el encabezado o pie de página. Hay tres secciones: izquierda, centro y derecha, representadas respectivamente por 0, 1 y 2.
  • Script – el script a utilizar para el encabezado o pie de página. Este script contiene comandos de script para formatear encabezados o pies de página.
from aspose.cells import Workbook
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# Instantiating a Workbook object
excel = Workbook()
# Obtaining the reference of the PageSetup of the worksheet
pageSetup = excel.worksheets[0].page_setup
# Setting worksheet name at the left section of the header
pageSetup.set_header(0, "&A")
# Setting current date and current time at the centeral section of the header
# and changing the font of the header
pageSetup.set_header(1, "&\"Times New Roman,Bold\"&D-&T")
# Setting current file name at the right section of the header and changing the
# font of the header
pageSetup.set_header(2, "&\"Times New Roman,Bold\"&12&F")
# Setting a string at the left section of the footer and changing the font
# of a part of this string ("123")
pageSetup.set_footer(0, "Hello World! &\"Courier New\"&14 123")
# Setting the current page number at the central section of the footer
pageSetup.set_footer(1, "&P")
# Setting page count at the right section of footer
pageSetup.set_footer(2, "&N")
# Save the Workbook.
excel.save("SetHeadersAndFooters_out.xls")

Cómo Insertar una Imagen en un Encabezado o Pie de Página

La clase PageSetup tiene dos métodos adicionales, set_header_picture y set_footer_picture, utilizados para agregar imágenes en el encabezado y pie de página. Estos métodos toman los siguientes parámetros:

  • Sección – la sección de encabezado o pie de página donde se colocará la imagen. Hay tres secciones, izquierda, centro y derecha, representadas por los valores 0, 1 y 2 respectivamente.
  • Arreglo de bytes – los datos gráficos (los datos binarios deben escribirse en el búfer de un arreglo de bytes).

Después de ejecutar el código a continuación y abrir el archivo, verificar el encabezado de la hoja de trabajo mediante:

  1. En el menú Archivo, seleccionar Configurar Página. Se mostrará un cuadro de diálogo.
  2. Seleccionar la pestaña Encabezado/Pie de página.
from aspose.cells import Workbook
import bytearray
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET
# The path to the documents directory.
dataDir = RunExamples.GetDataDir(".")
# Creating a Workbook object
workbook = Workbook()
# Creating a string variable to store the url of the logo/picture
logo_url = dataDir + "aspose-logo.jpg"
# Creating the instance of the FileStream object to open the logo/picture in the stream
inFile = open(logo_url, "rb")
# Instantiating the byte array of FileStream object's size
binaryData = bytearray(utils.filesize(inFile))
# Reads a block of bytes from the stream and writes data in a given buffer of byte array.
bytesRead = inFile.readinto(binaryData)
# Creating a PageSetup object to get the page settings of the first worksheet of the workbook
pageSetup = workbook.worksheets[0].page_setup
# Setting the logo/picture in the central section of the page header
pageSetup.set_header_picture(1, binaryData)
# Setting the script for the logo/picture
pageSetup.set_header(1, "&G")
# Setting the Sheet's name in the right section of the page header with the script
pageSetup.set_header(2, "&A")
# Saving the workbook
workbook.save(dataDir + "InsertImageInHeaderFooter_out.xls")
# Closing the FileStream object
inFile.close()