Introdução ao IronXL for Python
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 no seu servidor ou Interop. IronXL for Python fornece 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:
- .NET 6.0 SDK: IronXL for Python depende da biblioteca IronXL .NET, especificamente .NET 6.0, como sua tecnologia subjacente. Portanto, é necessário ter o .NET 6.0 SDK instalado na sua máquina para usar IronXL for Python.
- 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.
- Pip: Pip geralmente vem incluído na instalação do Python a partir da versão 3.4. No entanto, dependendo da sua instalação do Python, talvez seja necessário verificar se o pip já está instalado ou instalá-lo separadamente.
- Biblioteca IronXL : A biblioteca IronXL pode ser adicionada via pip. Use o comando abaixo para instalar o IronXL usando o pip:
==2023.x.x. Por exemplo, você pode executar o comando pip install ironxl==2023.x.x.pip3 em vez de pip para garantir que você está usando o Pip para 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.
# 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}'")
Criando novos documentos do Excel
Para criar documentos do Excel em Python, o IronXL for Python oferece uma interface simples e rápida.
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")
Exportação em CSV, XLS, XLSX, JSON ou XML
Também podemos salvar ou exportar diversos formatos de planilha estruturada comuns.
# 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")
Estilizando células e intervalos
As células e intervalos do Excel podem ser estilizados usando o objeto Estilo.
# Set cell's value and styles
workSheet["A1"].Value = "Hello World"
workSheet["A2"].Style.BottomBorder.SetColor("#ff6600")
workSheet["A2"].Style.BottomBorder.Type = BorderType.Double
Intervalos de classificação
Usando o IronXL for Python, podemos classificar um intervalo de células do Excel usando a função Range.
# 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()
Editando fórmulas
Editar uma fórmula do Excel é tão simples quanto atribuir um valor com um = sinal de igual no início. A fórmula será calculada em tempo real.
# Set a formula
workSheet["A1"].Formula = "=SUM(A2:A10)"
# Get the calculated value
sum_ = workSheet["A1"].DecimalValue
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 ao vivo compre uma licença. Licenças de teste de 30 dias também estão disponíveis.
Para nossa lista completa de exemplos de código, tutoriais, informações de licenciamento e documentação, visite: IronXL for Python.
Para mais suporte e perguntas, por favor contate nossa equipe.
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 bem estruturados e visualmente atraentes.