Introducción a IronXL for Python

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronXL for Python es una potente biblioteca desarrollada por Iron Software, que ofrece a los ingenieros de software la capacidad de crear, leer y editar archivos Excel (XLS, XLSX y CSV) en proyectos de Python 3.

IronXL for Python no requiere la instalación de Excel en el servidor ni Interop. IronXL for Python ofrece una API más rápida e intuitiva que Microsoft.Office.Interop.Excel.

IronXL for Python se basa en el éxito y la popularidad de IronXL for .NET.

Instalar IronXL for Python

Prerrequisitos

Para usar IronXL for Python, asegúrese de que la computadora tenga el siguiente software prerrequisito instalado:

  1. .NET 6.0 SDK: IronXL for Python se basa en la biblioteca IronXL .NET, específicamente .NET 6.0, como su tecnología subyacente. Por lo tanto, es necesario tener el .NET 6.0 SDK instalado en su máquina para usar IronXL for Python.
  2. Python: Descargue e instale la última versión de Python 3.x desde el sitio web oficial de Python: https://www.python.org/downloads/. Durante el proceso de instalación, asegúrese de seleccionar la opción para añadir Python al sistema PATH, lo que lo hará accesible desde la línea de comandos.
  3. Pip: Pip generalmente viene incluido con la instalación de Python a partir de Python 3.4 en adelante. Sin embargo, dependiendo de su instalación de Python, puede necesitar verificar si pip ya está instalado o instalarlo por separado.
  4. Biblioteca IronXL: La biblioteca IronXL se puede agregar a través de pip. Utilice el siguiente comando para instalar IronXL usando pip:
pip install IronXL

ConsejosPara instalar una versión específica de IronXL, utilice la siguiente sintaxis: ==2023.x.x. Por ejemplo, puede ejecutar el comando pip install ironxl==2023.x.x.

Posibles Problemas de Instalación En tales casos, es posible que necesites usar explícitamente el comando pip3 en lugar de pip para asegurarte de que estás usando Pip for Python 3.)}]

Leyendo un documento de Excel

Leer datos de un archivo Excel con IronXL for Python toma unas pocas líneas de código.

:path=/static-assets/excel-python/content-code-examples/get-started/get-started-1.py
# Load the necessary module from IronXL
from ironxl import WorkBook

# Load an existing Excel spreadsheet
# Replace 'sample.xlsx' with the path to your Excel file as needed.
workbook = WorkBook.load("sample.xlsx")

# Select the first worksheet from the workbook
worksheet = workbook.worksheets[0]

# Access cell A2 and get its integer value
# Ensure the correct method or property is used to fetch the integer value.
# Use 'value' to directly access the cell content.
cell_value = worksheet["A2"].value

# Print out the value of the cell A2
# Utilizing formatted strings for clear output
print(f"Cell A2 has value '{cell_value}'")

# Iterate over a range of cells and print their address and text content
# The range is defined from A2 to B10, which captures all rows in this interval.
for cell in worksheet.range("A2:B10"):
    # Access each cell in the specified range
    # AddressString is used to get the cell's location as a string, and Text to get its content.
    print(f"Cell {cell.address} has value '{cell.text}'")
PYTHON

Creación de nuevos documentos de Excel

Para crear documentos Excel en Python, IronXL for Python proporciona una interfaz sencilla y rápida.

:path=/static-assets/excel-python/content-code-examples/get-started/get-started-2.py
from ironxl import WorkBook, ExcelFileFormat, BorderType  # Import necessary classes from ironxl

# Create a new Excel WorkBook document in XLSX format
workbook = WorkBook.create(ExcelFileFormat.XLSX)

# Set metadata for the workbook
workbook.metadata.author = "IronXL"

# Add a new blank worksheet named "main_sheet" to the workbook
worksheet = workbook.create_worksheet("main_sheet")

# Add data to cell "A1"
worksheet["A1"].value = "Hello World"

# Set the style for cell "A2" with a double bottom border and a specific color
worksheet["A2"].style.bottom_border.set_color("#ff6600")
worksheet["A2"].style.bottom_border.type = BorderType.double

# Save the Excel file with the specified filename
workbook.save_as("NewExcelFile.xlsx")
PYTHON

Exportar como CSV, XLS, XLSX, JSON o XML

También podemos guardar o exportar en muchos formatos comunes de archivos de hojas de cálculo estructuradas.

:path=/static-assets/excel-python/content-code-examples/get-started/get-started-3.py
# Assuming workSheet is an existing instance of WorkSheet
workSheet.SaveAs("NewExcelFile.xls")
workSheet.SaveAs("NewExcelFile.xlsx")
workSheet.SaveAsCsv("NewExcelFile.csv")
workSheet.SaveAsJson("NewExcelFile.json")
workSheet.SaveAsXml("NewExcelFile.xml")
PYTHON

Dar estilo a celdas y rangos

Las celdas y rangos de Excel se pueden estilizar utilizando el objeto Style.

:path=/static-assets/excel-python/content-code-examples/get-started/get-started-4.py
# Set cell's value and styles
workSheet["A1"].Value = "Hello World"
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600")
workSheet["A2"].Style.BottomBorder.Type = BorderType.Double
PYTHON

Rangos de clasificación

Usando IronXL for Python podemos ordenar un rango de celdas de Excel usando Range.

:path=/static-assets/excel-python/content-code-examples/get-started/get-started-5.py
# Import IronXL library for handling Excel files
from ironxl import WorkBook

# Load an existing Excel workbook
# 'sample.xls' is the file name of the Excel workbook to be loaded
workbook = WorkBook.Load("sample.xls")

# Access the first worksheet in the workbook
# WorkSheets is the collection of all sheets in the workbook, 
# and we select the first one using index 0
worksheet = workbook.WorkSheets[0]

# Select a range of cells from A2 to A8 in the worksheet
# This specifies a contiguous range of cells starting from A2 and ending at A8
selected_range = worksheet["A2:A8"]

# Sort the selected range of cells in ascending order
# This operation reorders the values in the specified range from smallest to largest
selected_range.SortAscending()

# Save the changes made to the workbook, including the sorted range
# The workbook's state is updated with the changes after execution
workbook.Save()
PYTHON

Edición de fórmulas

Editar una fórmula de Excel es tan fácil como asignar un valor con un signo igual = al inicio. La fórmula se calculará en vivo.

:path=/static-assets/excel-python/content-code-examples/get-started/get-started-6.py
# Set a formula
workSheet["A1"].Formula = "=SUM(A2:A10)"
# Get the calculated value
sum_ = workSheet["A1"].DecimalValue
PYTHON

¿Por qué elegir IronXL for Python?

IronXL for Python presenta una API fácil para que los desarrolladores lean y escriban documentos Excel.

IronXL for Python no requiere la instalación de Microsoft Excel en su servidor ni Excel Interop para acceder a documentos Excel. Esto hace que trabajar con archivos Excel en Python sea una tarea muy rápida y sencilla.

Licencias y soporte disponibles

IronXL for Python es gratuito para uso y prueba en entornos de desarrollo.

Para usar en proyectos en vivo compre una licencia. Licencias de prueba de 30 días también están disponibles.

Para obtener nuestra lista completa de ejemplos de código, tutoriales, información sobre licencias y documentación, visite: IronXL for Python.

Para más asistencia y consultas, por favor pregunta a nuestro equipo.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Versión: 2026.3 recién lanzado
Still Scrolling Icon

¿Aún desplazándote?

¿Quieres una prueba rápida?
ejecuta una muestra observa cómo tus datos se convierten en una hoja de cálculo.