Introdução ao IronXL for Python

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

IronXL for Python é uma poderosa biblioteca desenvolvida pela Iron Software, que oferece aos engenheiros de software a capacidade de criar, ler e editar arquivos Excel (XLS, XLSX e CSV) em projetos Python 3.

IronXL for Python não requer que o Excel esteja instalado em seu servidor ou Interop. IronXL for Python oferece uma API mais rápida e intuitiva do que Microsoft.Office.Interop.Excel.

IronXL for Python baseia-se no sucesso e na popularidade do IronXL for .NET.

Instale o IronXL for Python

Pré-requisitos

Para usar o IronXL for Python, certifique-se de que o computador tenha o seguinte software pré-requisito instalado:

  1. SDK .NET 6.0 : O IronXL for Python utiliza a biblioteca IronXL .NET , especificamente o .NET 6.0, como tecnologia subjacente. Portanto, é necessário ter o SDK do .NET 6.0 instalado em sua máquina para usar o IronXL for Python.
  2. Python : Baixe e instale a versão mais recente do Python 3.x no site oficial do Python:https://www.python.org/downloads/ . Durante o processo de instalação, certifique-se de selecionar a opção para adicionar o Python ao PATH do sistema, o que o tornará acessível a partir da linha de comando.
  3. Pip : O Pip geralmente vem incluído na instalação do Python a partir da versão 3.4 e posteriores. No entanto, dependendo da sua instalação do Python, talvez seja necessário verificar se o pip já está instalado ou instalá-lo separadamente.
  4. Biblioteca IronXL : A biblioteca IronXL pode ser adicionada via pip. Use o comando abaixo para instalar o IronXL usando o pip:
pip install IronXL

PontasPara instalar uma versão específica do IronXL, use a seguinte sintaxe: ==2023.x.x. Por exemplo, você pode executar o comando pip install ironxl==2023.x.x.

ObserveEm alguns sistemas, o Python 2.x ainda pode ser a versão padrão. Em tais casos, pode ser necessário usar explicitamente o comando pip3 em vez de pip para garantir que você está usando o Pip for Python 3.

Como ler um documento do Excel

Ler dados de um arquivo Excel com o IronXL for Python requer apenas algumas linhas 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

Criando novos documentos do Excel

Para criar documentos do Excel em Python, o IronXL for Python oferece uma interface simples e 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

Exportação em CSV, XLS, XLSX, JSON ou XML

Também podemos salvar ou exportar diversos formatos de planilha estruturada comuns.

: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

Estilizando células e intervalos

As células e intervalos do Excel podem ser estilizados usando o objeto Estilo.

: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

Intervalos de classificação

Usando o IronXL for Python, podemos classificar um intervalo de células do Excel usando a função 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

Editando fórmulas

Editar uma fórmula do Excel é tão fácil quanto atribuir um valor com um sinal de igual = no início. A fórmula será calculada em tempo real.

: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 que escolher o IronXL for Python?

IronXL for Python oferece uma API fácil de usar para que os desenvolvedores leiam e escrevam documentos do Excel.

O IronXL for Python não requer a instalação do Microsoft Excel no seu servidor nem o uso do Excel Interop para acessar documentos do Excel. Isso torna o trabalho com arquivos do Excel em Python uma tarefa muito rápida e simples.

Licenciamento e suporte disponíveis

O IronXL for Python é gratuito para usar e testar em ambientes de desenvolvimento.

Para usar em projetos reais, adquira uma licença . Licenças de avaliação de 30 dias também estão disponíveis.

Para obter nossa lista completa de exemplos de código, tutoriais, informações sobre licenciamento e documentação, visite: IronXL for Python .

Para obter mais suporte e esclarecer dúvidas, entre em contato com nossa equipe .

Curtis Chau
Redator Técnico

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais ...

Leia mais
Pronto para começar?
Versão: 2026.3 acaba de ser lançado
Still Scrolling Icon

Ainda está rolando a tela?

Quer provas rápidas?
executar um exemplo Veja seus dados se transformarem em uma planilha.