Leer archivos de Excel con Python
Tabla de contenido
Instalar con Pip
pip install Spire.XLS
enlaces relacionados
Los archivos de Excel (hojas de cálculo) son utilizados por personas de todo el mundo para organizar, analizar y almacenar datos tabulares. Debido a su popularidad, los desarrolladores frecuentemente se encuentran con situaciones en las que necesitan extraer datos de Excel o crear informes en formato Excel. Siendo capaz de leer archivos de Excel con Python abre un amplio conjunto de posibilidades para el procesamiento y la automatización de datos. En este artículo, aprenderá cómo leer datos (texto o valores numéricos) de una celda, un rango de celdas o una hoja de trabajo completa utilizando la biblioteca Spire.XLS for Python.
- Leer datos de una celda particular en Python
- Leer datos de un rango de celdas en Python
- Leer datos de una hoja de cálculo de Excel en Python
- Leer valor en lugar de fórmula en una celda en Python
Biblioteca Python para leer Excel
Spire.XLS for Python es una biblioteca Python confiable de nivel empresarial para crear, escribir, leer y editando excel documentos (XLS, XLSX, XLSB, XLSM, ODS) en una aplicación Python. Proporciona un conjunto completo de interfaces, clases y propiedades que permiten a los programadores leer y escribir sobresalir archivos con facilidad. Específicamente, se puede acceder a una celda de un libro mediante la propiedad Worksheet.Range y se puede obtener el valor de la celda mediante la propiedad CellRange.Value.
La biblioteca es fácil de instalar ejecutando el siguiente comando pip. Si desea importar manualmente las dependencias necesarias, consulte Cómo instalar Spire.XLS for Python en VS Code
pip install Spire.XLS
Clases y propiedades en Spire.XLS para la API de Python
- Clase de libro de trabajo: representa un modelo de libro de trabajo de Excel, que puede usar para crear un libro de trabajo desde cero o cargar un documento de Excel existente y realizar modificaciones en él.
- Clase de hoja de trabajo: representa una hoja de trabajo en un libro de trabajo.
- Clase CellRange: representa una celda específica o un rango de celdas en un libro.
- Propiedad Worksheet.Range: obtiene una celda o un rango y devuelve un objeto de la clase CellRange.
- Propiedad Worksheet.AllocatedRange: obtiene el rango de celdas que contiene datos y devuelve un objeto de la clase CellRange.
- Propiedad CellRange.Value: obtiene el valor numérico o el valor de texto de una celda. Pero si una celda tiene una fórmula, esta propiedad devuelve la fórmula en lugar del resultado de la fórmula.
Leer datos de una celda particular en Python
Con Spire.XLS for Python, puede obtener fácilmente el valor de una determinada celda utilizando la propiedad CellRange.Value. Los pasos para leer datos de una celda particular de Excel en Python son los siguientes.
- Crear instancias de la clase de libro de trabajo
- Cargue un documento de Excel utilizando el método LoadFromFile.
- Obtenga una hoja de trabajo específica usando la propiedad Workbook.Worksheets[index].
- Obtenga una celda específica usando la propiedad Worksheet.Range.
- Obtenga el valor de la celda usando la propiedad CellRange.Value
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D9"]
# Get the value of the cell
print("D9 has the value: " + certainCell.Value)

Leer datos de un rango de celdas en Python
Ya sabemos cómo obtener el valor de una celda, para obtener los valores de un rango de celdas, como ciertas filas o columnas, solo necesitamos usar declaraciones de bucle para recorrer las celdas y luego extraerlas una por una. Los pasos para leer datos de un rango de celdas de Excel en Python son los siguientes.
- Crear instancias de la clase de libro de trabajo
- Cargue un documento de Excel utilizando el método LoadFromFile.
- Obtenga una hoja de trabajo específica usando la propiedad Workbook.Worksheets[index].
- Obtenga un rango de celdas específico usando la propiedad Worksheet.Range.
- Utilice declaraciones de bucle for para recuperar cada celda del rango y obtener el valor de una celda específica utilizando la propiedad CellRange.Value
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a cell range
cellRange = sheet.Range["A2:H5"]
# Iterate through the rows
for i in range(len(cellRange.Rows)):
# Iterate through the columns
for j in range(len(cellRange.Rows[i].Columns)):
# Get data of a specific cell
print(cellRange[i + 2, j + 1].Value + " ", end='')
print("")

Leer datos de una hoja de cálculo de Excel en Python
Spire.XLS for Python ofrece la propiedad Worksheet.AllocatedRange para obtener automáticamente el rango de celdas que contiene datos de una hoja de trabajo. Luego, recorremos las celdas dentro del rango de celdas en lugar de toda la hoja de trabajo y recuperamos los valores de las celdas uno por uno. Los siguientes son los pasos para leer datos de una hoja de cálculo de Excel en Python.
- Crear instancias de la clase de libro de trabajo.
- Cargue un documento de Excel utilizando el método LoadFromFile.
- Obtenga una hoja de trabajo específica usando la propiedad Workbook.Worksheets[index].
- Obtenga el rango de celdas que contiene datos de la hoja de trabajo usando la propiedad Worksheet.AllocatedRange.
- Utilice declaraciones de bucle for para recuperar cada celda del rango y obtener el valor de una celda específica utilizando la propiedad CellRange.Value.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get the first worksheet
sheet = wb.Worksheets[0]
# Get the cell range containing data
locatedRange = sheet.AllocatedRange
# Iterate through the rows
for i in range(len(sheet.Rows)):
# Iterate through the columns
for j in range(len(locatedRange.Rows[i].Columns)):
# Get data of a specific cell
print(locatedRange[i + 1, j + 1].Value + " ", end='')
print("")

Leer valor en lugar de fórmula en una celda en Python
Como se mencionó anteriormente, cuando una celda contiene una fórmula, la propiedad CellRange.Value devuelve la fórmula en sí, no el valor de la fórmula. Si queremos obtener el valor, debemos usar el método str(CellRange.FormulaValue). Los siguientes son los pasos para leer un valor en lugar de una fórmula en una celda de Excel en Python.
- Crear instancias de la clase de libro de trabajo.
- Cargue un documento de Excel utilizando el método LoadFromFile.
- Obtenga una hoja de trabajo específica usando la propiedad Workbook.Worksheets[index].
- Obtenga una celda específica usando la propiedad Worksheet.Range.
- Determine si la celda tiene fórmula usando la propiedad CellRange.HasFormula.
- Obtenga el valor de la fórmula de la celda usando el método str(CellRange.FormulaValue).
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Formula.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D4"]
# Determine if the cell has formula
if(certainCell.HasFormula):
# Get the formula value of the cell
print(str(certainCell.FormulaValue))

Conclusión
En esta publicación de blog, aprendimos cómo leer datos de celdas, regiones de celdas y hojas de trabajo en Python con la ayuda de Spire.XLS para la API de Python. También discutimos cómo determinar si una celda tiene una fórmula y cómo obtener el valor de la fórmula. Esta biblioteca admite la extracción de muchos otros elementos en Excel, como imágenes, hipervínculos y objetos OEL. Consulte nuestra documentación en línea para obtener más tutoriales. Si tiene alguna pregunta, comuníquese con nosotros por correo electrónico o en el foro.
Python으로 Excel 파일 읽기
목차
핍으로 설치
pip install Spire.XLS
관련된 링크들
Excel 파일(스프레드시트)은 전 세계 사람들이 표 형식의 데이터를 구성, 분석 및 저장하는 데 사용됩니다. 인기가 높기 때문에 개발자는 Excel에서 데이터를 추출하거나 Excel 형식으로 보고서를 작성해야 하는 상황에 자주 직면합니다. 를 할 수있는 Python으로 Excel 파일 읽기 데이터 처리 및 자동화를 위한 포괄적인 가능성을 열어줍니다. 이 기사에서는 다음 방법을 배웁니다. 셀, 셀 범위 또는 전체 워크시트에서 데이터(텍스트 또는 숫자 값)를 읽습니다 을 사용하여 Spire.XLS for Python 도서관.
Excel 읽기를 위한 Python 라이브러리
Spire.XLS for Python는 생성, 쓰기, 읽기 및 작업을 위한 신뢰할 수 있는 엔터프라이즈급 Python 라이브러리입니다 엑셀 편집 Python 응용 프로그램의 문서(XLS, XLSX, XLSB, XLSM, ODS). 이는 프로그래머가 읽고 사용할 수 있는 포괄적인 인터페이스, 클래스 및 속성 세트를 제공합니다 엑셀을 쓰다 파일을 쉽게. 특히 통합 문서의 셀은 Worksheet.Range 속성을 사용하여 액세스할 수 있으며 셀 값은 CellRange.Value 속성을 사용하여 얻을 수 있습니다.
라이브러리는 다음 pip 명령을 실행하여 쉽게 설치할 수 있습니다. 필요한 종속성을 수동으로 가져오려면 다음을 참조하세요 VS Code에서 Python용 Spire.XLS를 설치하는 방법
pip install Spire.XLS
Python API용 Spire.XLS의 클래스 및 속성
- 통합 문서 클래스: 처음부터 통합 문서를 만들거나 기존 Excel 문서를 로드하고 수정하는 데 사용할 수 있는 Excel 통합 문서 모델을 나타냅니다.
- Worksheet 클래스: 통합 문서의 워크시트를 나타냅니다.
- CellRange 클래스: 통합 문서의 특정 셀 또는 셀 범위를 나타냅니다.
- Worksheet.Range 속성: 셀 또는 범위를 가져오고 CellRange 클래스의 개체를 반환합니다.
- Worksheet.AllocatedRange 속성: 데이터가 포함된 셀 범위를 가져오고 CellRange 클래스의 개체를 반환합니다.
- CellRange.Value 속성: 셀의 숫자 값이나 텍스트 값을 가져옵니다. 그러나 셀에 수식이 있는 경우 이 속성은 수식 결과 대신 수식을 반환합니다.
Python에서 특정 셀의 데이터 읽기
Spire.XLS for Python를 사용하면 CellRange.Value 속성을 사용하여 특정 셀의 값을 쉽게 얻을 수 있습니다. Python에서 특정 Excel 셀의 데이터를 읽는 단계는 다음과 같습니다.
- 통합 문서 클래스 인스턴스화
- LoadFromFile 메서드를 사용하여 Excel 문서를 로드합니다.
- Workbook.Worksheets[index] 속성을 사용하여 특정 워크시트를 가져옵니다.
- Worksheet.Range 속성을 사용하여 특정 셀을 가져옵니다.
- CellRange.Value 속성을 사용하여 셀 값을 가져옵니다.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D9"]
# Get the value of the cell
print("D9 has the value: " + certainCell.Value)

Python의 셀 범위에서 데이터 읽기
우리는 셀의 값을 얻는 방법, 즉 특정 행이나 열과 같은 셀 범위의 값을 얻는 방법을 이미 알고 있습니다. 루프 문을 사용하여 셀을 반복한 다음 하나씩 추출하면 됩니다. Python에서 Excel 셀 범위의 데이터를 읽는 단계는 다음과 같습니다.
- 통합 문서 클래스 인스턴스화.
- LoadFromFile 메서드를 사용하여 Excel 문서를 로드합니다.
- Workbook.Worksheets[index] 속성을 사용하여 특정 워크시트를 가져옵니다.
- Worksheet.Range 속성을 사용하여 특정 셀 범위를 가져옵니다.
- for 루프 문을 사용하여 범위의 각 셀을 검색하고 CellRange.Value 속성을 사용하여 특정 셀의 값을 가져옵니다.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a cell range
cellRange = sheet.Range["A2:H5"]
# Iterate through the rows
for i in range(len(cellRange.Rows)):
# Iterate through the columns
for j in range(len(cellRange.Rows[i].Columns)):
# Get data of a specific cell
print(cellRange[i + 2, j + 1].Value + " ", end='')
print("")

Python에서 Excel 워크시트의 데이터 읽기
Spire.XLS for Python는 워크시트의 데이터가 포함된 셀 범위를 자동으로 얻기 위해 Worksheet.AllocationRange 속성을 제공합니다. 그런 다음 전체 워크시트가 아닌 셀 범위 내의 셀을 순회하여 셀 값을 하나씩 검색합니다. 다음은 Python에서 Excel 워크시트의 데이터를 읽는 단계입니다.
- 통합 문서 클래스 인스턴스화.
- LoadFromFile 메서드를 사용하여 Excel 문서를 로드합니다.
- Workbook.Worksheets[index] 속성을 사용하여 특정 워크시트를 가져옵니다.
- Worksheet.AllocationRange 속성을 사용하여 워크시트의 데이터가 포함된 셀 범위를 가져옵니다.
- for 루프 문을 사용하여 범위의 각 셀을 검색하고 CellRange.Value 속성을 사용하여 특정 셀의 값을 가져옵니다.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get the first worksheet
sheet = wb.Worksheets[0]
# Get the cell range containing data
locatedRange = sheet.AllocatedRange
# Iterate through the rows
for i in range(len(sheet.Rows)):
# Iterate through the columns
for j in range(len(locatedRange.Rows[i].Columns)):
# Get data of a specific cell
print(locatedRange[i + 1, j + 1].Value + " ", end='')
print("")

Python의 셀에서 수식 대신 값 읽기
앞에서 언급한 것처럼 셀에 수식이 포함된 경우 CellRange.Value 속성은 수식 값이 아닌 수식 자체를 반환합니다. 값을 얻으려면 str(CellRange.FormulaValue) 메서드를 사용해야 합니다. 다음은 Python에서 Excel 셀의 수식이 아닌 값을 읽는 단계입니다.
- 통합 문서 클래스 인스턴스화.
- LoadFromFile 메서드를 사용하여 Excel 문서를 로드합니다.
- Workbook.Worksheets[index] 속성을 사용하여 특정 워크시트를 가져옵니다.
- Worksheet.Range 속성을 사용하여 특정 셀을 가져옵니다.
- CellRange.HasFormula 속성을 사용하여 셀에 수식이 있는지 확인합니다.
- str(CellRange.FormulaValue) 메서드를 사용하여 셀의 수식 값을 가져옵니다.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Formula.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D4"]
# Determine if the cell has formula
if(certainCell.HasFormula):
# Get the formula value of the cell
print(str(certainCell.FormulaValue))

결론
이 블로그 게시물에서는 Python API용 Spire.XLS를 사용하여 Python에서 셀, 셀 영역 및 워크시트의 데이터를 읽는 방법을 배웠습니다. 또한 셀에 수식이 있는지 확인하는 방법과 수식의 값을 얻는 방법도 논의했습니다. 이 라이브러리는 이미지와 같은 Excel의 다른 많은 요소 추출을 지원합니다. 하이퍼링크 및 OEL 객체. 우리를 확인해보세요 온라인 문서 더 많은 튜토리얼을 보려면. 질문이 있으시면 다음으로 문의해 주세요 이메일 이나 포럼에서.
Leggere file Excel con Python
Sommario
Installa con Pip
pip install Spire.XLS
Link correlati
I file Excel (fogli di calcolo) vengono utilizzati da persone in tutto il mondo per organizzare, analizzare e archiviare dati tabulari. A causa della loro popolarità, gli sviluppatori incontrano spesso situazioni in cui devono estrarre dati da Excel o creare report in formato Excel. Essere capace di leggere file Excel con Python apre una serie completa di possibilità per l'elaborazione e l'automazione dei dati. In questo articolo imparerai come farlo leggere dati (valori di testo o numerici) da una cella, un intervallo di celle o un intero foglio di lavoro utilizzando la libreria Spire.XLS for Python library.
- Leggi i dati di una cella particolare in Python
- Leggi i dati da un intervallo di celle in Python
- Leggere i dati da un foglio di lavoro Excel in Python
- Leggi il valore anziché la formula in una cella in Python
Libreria Python per leggere Excel
Spire.XLS for Python è una libreria Python affidabile di livello aziendale per creare, scrivere, leggere e modifica Excel documenti (XLS, XLSX, XLSB, XLSM, ODS) in un'applicazione Python. Fornisce un set completo di interfacce, classi e proprietà che consentono ai programmatori di leggere e scrivere Excel file con facilità. Nello specifico, è possibile accedere a una cella in una cartella di lavoro utilizzando la proprietà Worksheet.Range e il valore della cella può essere ottenuto utilizzando la proprietà CellRange.Value.
La libreria è facile da installare eseguendo il seguente comando pip. Se desideri importare manualmente le dipendenze necessarie, fai riferimento a Come installare Spire.XLS for Python in VS Code
pip install Spire.XLS
Classi e proprietà in Spire.XLS per l'API Python
- Classe cartella di lavoro: rappresenta un modello di cartella di lavoro Excel, che è possibile utilizzare per creare una cartella di lavoro da zero o caricare un documento Excel esistente e apportarvi modifiche.
- Classe del foglio di lavoro: rappresenta un foglio di lavoro in una cartella di lavoro.
- Classe CellRange: rappresenta una cella specifica o un intervallo di celle in una cartella di lavoro.
- Proprietà Worksheet.Rangeottiene una cella o un intervallo e restituisce un oggetto della classe CellRange.
- ProprietàWorksheet.AllocatedRange: ottiene l'intervallo di celle contenente dati e restituisce un oggetto della classe CellRange.
- ProprietàCellRange.Value: ottiene il valore numerico o il valore testo di una cella. Ma se una cella contiene una formula, questa proprietà restituisce la formula anziché il risultato della formula.
Leggi i dati di una cella particolare in Python
Con Spire.XLS for Python, puoi ottenere facilmente il valore di una determinata cella utilizzando la proprietà CellRange.Value. I passaggi per leggere i dati di una particolare cella Excel in Python sono i seguenti.
- Crea un'istanza della classe Workbook
- Carica un documento Excel utilizzando il metodo LoadFromFile.
- Ottieni un foglio di lavoro specifico utilizzando la proprietà Workbook.Worksheets[index].
- Ottieni una cella specifica utilizzando la proprietà Worksheet.Range.
- Ottieni il valore della cella utilizzando la proprietà CellRange.Value
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D9"]
# Get the value of the cell
print("D9 has the value: " + certainCell.Value)

Leggi i dati da un intervallo di celle in Python
Sappiamo già come ottenere il valore di una cella, per ottenere i valori di un intervallo di celle, come determinate righe o colonne, dobbiamo solo utilizzare le istruzioni di loop per scorrere le celle e quindi estrarle una per una. I passaggi per leggere i dati da un intervallo di celle Excel in Python sono i seguenti.
- Crea un'istanza della classe Workbook
- Carica un documento Excel utilizzando il metodo LoadFromFile.
- Ottieni un foglio di lavoro specifico utilizzando la proprietà Workbook.Worksheets[index].
- Ottieni un intervallo di celle specifico utilizzando la proprietà Worksheet.Range.
- Utilizzare le istruzioni del ciclo for per recuperare ogni cella nell'intervallo e ottenere il valore di una cella specifica utilizzando la proprietà CellRange.Value
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a cell range
cellRange = sheet.Range["A2:H5"]
# Iterate through the rows
for i in range(len(cellRange.Rows)):
# Iterate through the columns
for j in range(len(cellRange.Rows[i].Columns)):
# Get data of a specific cell
print(cellRange[i + 2, j + 1].Value + " ", end='')
print("")

Leggere i dati da un foglio di lavoro Excel in Python
Spire.XLS for Python offre la proprietà Worksheet.AllocatedRange per ottenere automaticamente l'intervallo di celle che contiene i dati da un foglio di lavoro. Quindi, attraversiamo le celle all'interno dell'intervallo di celle anziché l'intero foglio di lavoro e recuperiamo i valori delle celle uno per uno. Di seguito sono riportati i passaggi per leggere i dati da un foglio di lavoro Excel in Python.
- Crea un'istanza della classe Workbook.
- Carica un documento Excel utilizzando il metodo LoadFromFile.
- Ottieni un foglio di lavoro specifico utilizzando la proprietà Workbook.Worksheets[index].
- Ottieni l'intervallo di celle contenente i dati dal foglio di lavoro utilizzando la proprietà Worksheet.AllocatedRange.
- Utilizzare le istruzioni del ciclo for per recuperare ogni cella nell'intervallo e ottenere il valore di una cella specifica utilizzando la proprietà CellRange.Value.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get the first worksheet
sheet = wb.Worksheets[0]
# Get the cell range containing data
locatedRange = sheet.AllocatedRange
# Iterate through the rows
for i in range(len(sheet.Rows)):
# Iterate through the columns
for j in range(len(locatedRange.Rows[i].Columns)):
# Get data of a specific cell
print(locatedRange[i + 1, j + 1].Value + " ", end='')
print("")

Leggi il valore anziché la formula in una cella in Python
Come accennato in precedenza, quando una cella contiene una formula, la proprietà CellRange.Value restituisce la formula stessa, non il valore della formula. Se vogliamo ottenere il valore, dobbiamo utilizzare il metodo str(CellRange.FormulaValue). Di seguito sono riportati i passaggi per leggere il valore anziché la formula in una cella di Excel in Python.
- Crea un'istanza della classe Workbook.
- Carica un documento Excel utilizzando il metodo LoadFromFile.
- Ottieni un foglio di lavoro specifico utilizzando la proprietà Workbook.Worksheets[index].
- Ottieni una cella specifica utilizzando la proprietà Worksheet.Range.
- Determina se la cella ha una formula utilizzando la proprietà CellRange.HasFormula.
- Ottieni il valore della formula della cella utilizzando il metodo str(CellRange.FormulaValue).
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Formula.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D4"]
# Determine if the cell has formula
if(certainCell.HasFormula):
# Get the formula value of the cell
print(str(certainCell.FormulaValue))

Conclusione
In questo post del blog, abbiamo imparato come leggere i dati da celle, regioni di celle e fogli di lavoro in Python con l'aiuto dell'API Spire.XLS for Python. Abbiamo anche discusso come determinare se una cella ha una formula e come ottenere il valore della formula. Questa libreria supporta l'estrazione di molti altri elementi in Excel come immagini, collegamenti ipertestuali e oggetti OEL. Consulta la nostra documentazione online per ulteriori tutorial. Se avete domande, contattateci via e-mail o sul forum.
Lire des fichiers Excel avec Python
Table des matières
- Bibliothèque Python pour lire Excel
- Classes et propriétés dans Spire.XLS pour l'API Python
- Lire les données d'une cellule particulière
- Lire les données d'une plage de cellules
- Lire les données d'une feuille de calcul Excel
- Lire la valeur plutôt que la formule dans une cellule
- Conclusion
- Voir également
Installer avec Pip
pip install Spire.XLS
Liens connexes
Les fichiers Excel (feuilles de calcul) sont utilisés par des personnes du monde entier pour organiser, analyser et stocker des données tabulaires. En raison de leur popularité, les développeurs sont fréquemment confrontés à des situations dans lesquelles ils doivent extraire des données d'Excel ou créer des rapports au format Excel. Être capable de lire des fichiers Excel avec Python ouvre un ensemble complet de possibilités pour le traitement et l’automatisation des données. Dans cet article, vous apprendrez comment lire des données (valeurs de texte ou numériques) à partir d'une cellule, d'une plage de cellules ou d'une feuille de calcul entière en utilisant la bibliothèque Spire.XLS for Python.
- Lire les données d'une cellule particulière en Python
- Lire les données d'une plage de cellules en Python
- Lire les données d'une feuille de calcul Excel en Python
- Lire la valeur plutôt que la formule dans une cellule en Python
Bibliothèque Python pour lire Excel
Spire.XLS for Python est une bibliothèque Python fiable au niveau de l'entreprise pour créer, écrire, lire et édition d'Excel documents (XLS, XLSX, XLSB, XLSM, ODS) dans une application Python. Il fournit un ensemble complet d'interfaces, de classes et de propriétés qui permettent aux programmeurs de lire et écrire Excel fichiers en toute simplicité. Plus précisément, une cellule d'un classeur est accessible à l'aide de la propriété Worksheet.Range et la valeur de la cellule peut être obtenue à l'aide de la propriété CellRange.Value.
La bibliothèque est facile à installer en exécutant la commande pip suivante. Si vous souhaitez importer manuellement les dépendances nécessaires, reportez-vous à Comment installer Spire.XLS for Python dans VS Code
pip install Spire.XLS
Classes et propriétés dans Spire.XLS pour l'API Python
- Classe de classeur: représente un modèle de classeur Excel, que vous pouvez utiliser pour créer un classeur à partir de zéro ou charger un document Excel existant et y apporter des modifications.
- Classe Worksheet: représente une feuille de calcul dans un classeur.
- Classe CellRange: représente une cellule spécifique ou une plage de cellules dans un classeur.
- Propriété Worksheet.Range : obtient une cellule ou une plage et renvoie un objet de la classe CellRange.
- Propriété Worksheet.AllocatedRange: obtient la plage de cellules contenant les données et renvoie un objet de la classe CellRange.
- Propriété CellRange.Value: obtient la valeur numérique ou la valeur textuelle d'une cellule. Mais si une cellule contient une formule, cette propriété renvoie la formule au lieu du résultat de la formule.
Lire les données d'une cellule particulière en Python
Avec Spire.XLS for Python, vous pouvez facilement obtenir la valeur d'une certaine cellule en utilisant la propriété CellRange.Value. Les étapes pour lire les données d'une cellule Excel particulière en Python sont les suivantes.
- Instancier la classe Workbook
- Chargez un document Excel à l'aide de la méthode LoadFromFile.
- Obtenez une feuille de calcul spécifique à l’aide de la propriété Workbook.Worksheets[index].
- Obtenez une cellule spécifique à l’aide de la propriété Worksheet.Range.
- Obtenez la valeur de la cellule à l'aide de la propriété CellRange.Value
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D9"]
# Get the value of the cell
print("D9 has the value: " + certainCell.Value)

Lire les données d'une plage de cellules en Python
Nous savons déjà comment obtenir la valeur d'une cellule, pour obtenir les valeurs d'une plage de cellules, comme certaines lignes ou colonnes, il suffit d'utiliser des instructions de boucle pour parcourir les cellules, puis de les extraire une par une. Les étapes pour lire les données d'une plage de cellules Excel en Python sont les suivantes.
- Instancier la classe Workbook.
- Chargez un document Excel à l'aide de la méthode LoadFromFile.
- Obtenez une feuille de calcul spécifique à l’aide de la propriété Workbook.Worksheets[index].
- Obtenez une plage de cellules spécifique à l’aide de la propriété Worksheet.Range.
- Utilisez les instructions de boucle for pour récupérer chaque cellule de la plage et obtenir la valeur d'une cellule spécifique à l'aide de la propriété CellRange.Value.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a cell range
cellRange = sheet.Range["A2:H5"]
# Iterate through the rows
for i in range(len(cellRange.Rows)):
# Iterate through the columns
for j in range(len(cellRange.Rows[i].Columns)):
# Get data of a specific cell
print(cellRange[i + 2, j + 1].Value + " ", end='')
print("")

Lire les données d'une feuille de calcul Excel en Python
Spire.XLS for Python propose la propriété Worksheet.AllocatedRange pour obtenir automatiquement la plage de cellules contenant les données d'une feuille de calcul. Ensuite, nous parcourons les cellules de la plage de cellules plutôt que la feuille de calcul entière et récupérons les valeurs des cellules une par une. Voici les étapes pour lire les données d'une feuille de calcul Excel en Python.
- Instancier la classe Workbook
- Chargez un document Excel à l'aide de la méthode LoadFromFile.
- Obtenez une feuille de calcul spécifique à l’aide de la propriété Workbook.Worksheets[index].
- Obtenez la plage de cellules contenant les données de la feuille de calcul à l’aide de la propriété Worksheet.AllocatedRange.
- Utilisez les instructions de boucle for pour récupérer chaque cellule de la plage et obtenir la valeur d'une cellule spécifique à l'aide de la propriété CellRange.Value.
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get the first worksheet
sheet = wb.Worksheets[0]
# Get the cell range containing data
locatedRange = sheet.AllocatedRange
# Iterate through the rows
for i in range(len(sheet.Rows)):
# Iterate through the columns
for j in range(len(locatedRange.Rows[i].Columns)):
# Get data of a specific cell
print(locatedRange[i + 1, j + 1].Value + " ", end='')
print("")

Lire la valeur plutôt que la formule dans une cellule en Python
Comme mentionné précédemment, lorsqu'une cellule contient une formule, la propriété CellRange.Value renvoie la formule elle-même, et non la valeur de la formule. Si nous voulons obtenir la valeur, nous devons utiliser la méthode str(CellRange.FormulaValue). Voici les étapes pour lire la valeur plutôt que la formule dans une cellule Excel en Python.
- Instancier la classe Workbook.
- Chargez un document Excel à l'aide de la méthode LoadFromFile.
- Obtenez une feuille de calcul spécifique à l’aide de la propriété Workbook.Worksheets[index].
- Obtenez une cellule spécifique à l’aide de la propriété Worksheet.Range.
- Déterminez si la cellule a une formule à l’aide de la propriété CellRange.HasFormula.
- Obtenez la valeur de formule de la cellule à l'aide de la méthode str(CellRange.FormulaValue).
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Formula.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D4"]
# Determine if the cell has formula
if(certainCell.HasFormula):
# Get the formula value of the cell
print(str(certainCell.FormulaValue))

Conclusion
Dans cet article de blog, nous avons appris à lire les données de cellules, de régions de cellules et de feuilles de calcul en Python à l'aide de l'API Spire.XLS for Python. Nous avons également expliqué comment déterminer si une cellule contient une formule et comment obtenir la valeur de la formule. Cette bibliothèque prend en charge l'extraction de nombreux autres éléments dans Excel tels que des images, des hyperliens et des objets OEL. Consultez notre documentation en ligne pour plus de tutoriels. Si vous avez des questions, n'hésitez pas à nous contacter par email ou sur le forum.
Lesen Sie Excel-Dateien mit Python
Inhaltsverzeichnis
Mit Pip installieren
pip install Spire.XLS
verwandte Links
Excel-Dateien (Tabellenkalkulationen) werden von Menschen weltweit zum Organisieren, Analysieren und Speichern tabellarischer Daten verwendet. Aufgrund ihrer Beliebtheit geraten Entwickler häufig in Situationen, in denen sie Daten aus Excel extrahieren oder Berichte im Excel-Format erstellen müssen. Fähig sein zu Lesen Sie Excel-Dateien mit Python eröffnet umfassende Möglichkeiten der Datenverarbeitung und Automatisierung. In diesem Artikel erfahren Sie, wie das geht Lesen Sie Daten (Text- oder Zahlenwerte) aus einer Zelle, einem Zellbereich oder einem gesamten Arbeitsblatt durch Verwendung der Spire.XLS for Python-Bibliothek
- Lesen Sie Daten einer bestimmten Zelle in Python
- Lesen Sie Daten aus einem Zellbereich in Python
- Lesen Sie Daten aus einem Excel-Arbeitsblatt in Python
- Lesen Sie in Python einen Wert statt einer Formel in einer Zelle
Python-Bibliothek zum Lesen von Excel
Spire.XLS for Python ist eine zuverlässige Python-Bibliothek auf Unternehmensebene zum Erstellen, Schreiben, Lesen und Bearbeiten von Excel-Dokumenten (XLS, XLSX, XLSB, XLSM, ODS) in einer Python-Anwendung. Es bietet einen umfassenden Satz an Schnittstellen, Klassen und Eigenschaften, die es Programmierern ermöglichen, Excel -Dateien problemlos zu lesen und zu schreiben. Insbesondere kann mit der Worksheet.Range-Eigenschaft auf eine Zelle in einer Arbeitsmappe zugegriffen werden und der Wert der Zelle kann mit der CellRange.Value-Eigenschaft abgerufen werden.
Die Bibliothek lässt sich einfach installieren, indem Sie den folgenden pip-Befehl ausführen. Wenn Sie die erforderlichen Abhängigkeiten manuell importieren möchten, lesen Sie weiter So installieren Sie Spire.XLS for Python in VS Code
pip install Spire.XLS
Klassen und Eigenschaften in Spire.XLS for die Python-API
- Arbeitsmappenklasse: Stellt ein Excel-Arbeitsmappenmodell dar, mit dem Sie eine Arbeitsmappe von Grund auf erstellen oder ein vorhandenes Excel-Dokument laden und Änderungen daran vornehmen können.
- Arbeitsblattklasse: Stellt ein Arbeitsblatt in einer Arbeitsmappe dar.
- CellRange-Klasse: Stellt eine bestimmte Zelle oder einen Zellbereich in einer Arbeitsmappe dar.
- Worksheet.Range-Eigenschaft: Ruft eine Zelle oder einen Bereich ab und gibt ein Objekt der CellRange-Klasse zurück.
- Worksheet.AllocatedRange-Eigenschaft: Ruft den Zellbereich mit Daten ab und gibt ein Objekt der CellRange-Klasse zurück.
- CellRange.Value-Eigenschaft: Ruft den Zahlenwert oder Textwert einer Zelle ab. Wenn eine Zelle jedoch eine Formel enthält, gibt diese Eigenschaft die Formel anstelle des Ergebnisses der Formel zurück.
Lesen Sie Daten einer bestimmten Zelle in Python
Mit Spire.XLS for Python können Sie mithilfe der CellRange.Value-Eigenschaft ganz einfach den Wert einer bestimmten Zelle ermitteln. Die Schritte zum Lesen von Daten einer bestimmten Excel-Zelle in Python sind wie folgt.
- Arbeitsmappenklasse instanziieren
- Laden Sie ein Excel-Dokument mit der LoadFromFile-Methode.
- Rufen Sie ein bestimmtes Arbeitsblatt mit der Eigenschaft Workbook.Worksheets[index] ab.
- Rufen Sie eine bestimmte Zelle mithilfe der Worksheet.Range-Eigenschaft ab.
- Rufen Sie den Wert der Zelle mithilfe der CellRange.Value-Eigenschaft ab
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D9"]
# Get the value of the cell
print("D9 has the value: " + certainCell.Value)

Lesen Sie Daten aus einem Zellbereich in Python
Wir wissen bereits, wie man den Wert einer Zelle erhält, um die Werte eines Zellbereichs, wie z. B. bestimmter Zeilen oder Spalten, zu erhalten. Wir müssen lediglich Schleifenanweisungen verwenden, um die Zellen zu durchlaufen und sie dann einzeln zu extrahieren. Die Schritte zum Lesen von Daten aus einem Excel-Zellenbereich in Python sind wie folgt.
- Arbeitsmappenklasse instanziieren
- Laden Sie ein Excel-Dokument mit der LoadFromFile-Methode.
- Rufen Sie ein bestimmtes Arbeitsblatt mit der Eigenschaft Workbook.Worksheets[index] ab.
- Rufen Sie mithilfe der Worksheet.Range-Eigenschaft einen bestimmten Zellbereich ab.
- Verwenden Sie for-Schleifenanweisungen, um jede Zelle im Bereich abzurufen und den Wert einer bestimmten Zelle mithilfe der CellRange.Value-Eigenschaft abzurufen
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a cell range
cellRange = sheet.Range["A2:H5"]
# Iterate through the rows
for i in range(len(cellRange.Rows)):
# Iterate through the columns
for j in range(len(cellRange.Rows[i].Columns)):
# Get data of a specific cell
print(cellRange[i + 2, j + 1].Value + " ", end='')
print("")

Lesen Sie Daten aus einem Excel-Arbeitsblatt in Python
Spire.XLS for Python offers bietet die Worksheet.AllocatedRange-Eigenschaft, um automatisch den Zellbereich abzurufen, der Daten aus einem Arbeitsblatt enthält. Anschließend durchlaufen wir die Zellen innerhalb des Zellbereichs und nicht das gesamte Arbeitsblatt und rufen die Zellwerte einzeln ab. Im Folgenden finden Sie die Schritte zum Lesen von Daten aus einem Excel-Arbeitsblatt in Python.
- Arbeitsmappenklasse instanziieren
- Laden Sie ein Excel-Dokument mit der LoadFromFile-Methode.
- Rufen Sie ein bestimmtes Arbeitsblatt mit der Eigenschaft Workbook.Worksheets[index] ab.
- Rufen Sie mithilfe der Worksheet.AllocatedRange-Eigenschaft den Zellbereich mit Daten aus dem Arbeitsblatt ab.
- Verwenden Sie for-Schleifenanweisungen, um jede Zelle im Bereich abzurufen und den Wert einer bestimmten Zelle mithilfe der CellRange.Value-Eigenschaft abzurufen
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an existing Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Data.xlsx");
# Get the first worksheet
sheet = wb.Worksheets[0]
# Get the cell range containing data
locatedRange = sheet.AllocatedRange
# Iterate through the rows
for i in range(len(sheet.Rows)):
# Iterate through the columns
for j in range(len(locatedRange.Rows[i].Columns)):
# Get data of a specific cell
print(locatedRange[i + 1, j + 1].Value + " ", end='')
print("")

Lesen Sie in Python einen Wert statt einer Formel in einer Zelle
Wie bereits erwähnt, gibt die CellRange.Value-Eigenschaft die Formel selbst zurück, wenn eine Zelle eine Formel enthält, nicht den Wert der Formel. Wenn wir den Wert erhalten möchten, müssen wir die Methode str(CellRange.FormulaValue) verwenden. Im Folgenden finden Sie die Schritte zum Lesen von Werten anstelle von Formeln in einer Excel-Zelle in Python.
- Arbeitsmappenklasse instanziieren
- Laden Sie ein Excel-Dokument mit der LoadFromFile-Methode.
- Rufen Sie ein bestimmtes Arbeitsblatt mit der Eigenschaft Workbook.Worksheets[index] ab.
- Rufen Sie eine bestimmte Zelle mithilfe der Worksheet.Range-Eigenschaft ab.
- Bestimmen Sie mithilfe der CellRange.HasFormula-Eigenschaft, ob die Zelle über eine Formel verfügt.
- Rufen Sie den Formelwert der Zelle mit der Methode str(CellRange.FormulaValue) ab
- Python
from spire.xls import *
from spire.xls.common import *
# Create a Workbook object
wb = Workbook()
# Load an Excel file
wb.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Formula.xlsx");
# Get a specific worksheet
sheet = wb.Worksheets[0]
# Get a specific cell
certainCell = sheet.Range["D4"]
# Determine if the cell has formula
if(certainCell.HasFormula):
# Get the formula value of the cell
print(str(certainCell.FormulaValue))

Abschluss
In diesem Blogbeitrag haben wir gelernt, wie man mithilfe der Spire.XLS for Python-API Daten aus Zellen, Zellregionen und Arbeitsblättern in Python liest. Wir haben auch besprochen, wie man ermittelt, ob eine Zelle eine Formel hat und wie man den Wert der Formel erhält. Diese Bibliothek unterstützt die Extraktion vieler anderer Elemente in Excel wie Bilder, Hyperlinks und OEL-Objekte. Weitere Tutorials finden Sie in unserer Online-Dokumentation. Wenn Sie Fragen haben, kontaktieren Sie uns bitte per E-Mail oder im Forum.
Python: Merge Word Documents
Table of Contents
Install with Pip
pip install Spire.Doc
Related Links
Dealing with a large number of Word documents can be very challenging. Whether it's editing or reviewing a large number of documents, there's a lot of time wasted on opening and closing documents. What's more, sharing and receiving a large number of separate Word documents can be annoying, as it may require a lot of repeated sending and receiving operations by both the sharer and the receiver. Therefore, in order to enhance efficiency and save time, it is advisable to merge related Word documents into a single file. From this article, you will know how to use Spire.Doc for Python to easily merge Word documents through Python programs.
- Merge Word Documents by Inserting Files with Python
- Merge Word Documents by Cloning Contents with Python
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip command.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python in VS Code
Merge Word Documents by Inserting Files with Python
The method Document.insertTextFromFile() is used to insert other Word documents to the current one, and the inserted content will start from a new page. The detailed steps for merging Word documents by inserting are as follows:
- Create an object of Document class and load a Word document using Document.LoadFromFile() method.
- Insert the content from another document to it using Document.InsertTextFromFile() method.
- Save the document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")
# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)
# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Merge Word Documents by Cloning Contents with Python
Merging Word documents can also be achieved by cloning contents from one Word document to another. This method maintains the formatting of the original document, and content cloned from another document continues at the end of the current document without starting a new Page. The detailed steps are as follows:
- Create two objects of Document class and load two Word documents using Document.LoadFromFile() method.
- Get the last section of the destination document using Document.Sections.get_Item() method.
- Loop through the sections in the document to be cloned and then loop through the child objects of the sections.
- Get a section child object using Section.Body.ChildObjects.get_Item() method.
- Add the child object to the last section of the destination document using Section.Body.ChildObjects.Add() method.
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")
# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)
# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
section = doc2.Sections.get_Item(i)
# Loop through the child objects in the sections
for j in range(section.Body.ChildObjects.Count):
obj = section.Body.ChildObjects.get_Item(j)
# Add the child objects from the second document to the last section of the first document
lastSection.Body.ChildObjects.Add(obj.Clone())
# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Python: mesclar documentos do Word
Índice
Instalar com Pip
pip install Spire.Doc
Links Relacionados
Lidar com um grande número de documentos do Word pode ser muito desafiador. Seja editando ou revisando um grande número de documentos, há muito tempo perdido abrindo e fechando documentos. Além do mais, compartilhar e receber um grande número de documentos Word separados pode ser irritante, pois pode exigir muitas operações repetidas de envio e recebimento tanto por parte do compartilhador quanto do destinatário. Portanto, para aumentar a eficiência e economizar tempo, é aconselhável mesclar documentos do Word relacionados em um único arquivo. Neste artigo, você saberá como usar Spire.Doc for Python para facilmente mesclar documentos do Word através de programas Python.
- Mesclar documentos do Word inserindo arquivos com Python
- Mesclar documentos do Word clonando conteúdo com Python
Instale Spire.Doc for Python
Este cenário requer Spire.Doc for Python e plum-dispatch v1.7.4. Eles podem ser facilmente instalados em seu VS Code por meio do seguinte comando pip.
pip install Spire.Doc
Se você não tiver certeza de como instalar, consulte este tutorial: Como instalar Spire.Doc for Python no código VS
Mesclar documentos do Word inserindo arquivos com Python
O método Document.insertTextFromFile() é usado para inserir outros documentos do Word ao atual, e o conteúdo inserido começará a partir de uma nova página. As etapas detalhadas para mesclar documentos do Word por inserção são as seguintes:
- Crie um objeto da classe Document e carregue um documento Word usando o método Document.LoadFromFile().
- Insira o conteúdo de outro documento nele usando o método Document.InsertTextFromFile().
- Save the document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")
# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)
# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Mesclar documentos do Word clonando conteúdo com Python
A mesclagem de documentos do Word também pode ser obtida clonando o conteúdo de um documento do Word para outro. Este método mantém a formatação do documento original e o conteúdo clonado de outro documento continua no final do documento atual sem iniciar uma nova página. As etapas detalhadas são as seguintes:
- Crie dois objetos da classe Document e carregue dois documentos do Word usando o método Document.LoadFromFile().
- Obtenha a última seção do documento de destino usando o método Document.Sections.get_Item().
- Percorra as seções do documento a ser clonado e, em seguida, percorra os objetos filhos das seções.
- Obtenha um objeto filho de seção usando o método Section.Body.ChildObjects.get_Item().
- Adicione o objeto filho à última seção do documento de destino usando o método Section.Body.ChildObjects.Add().
- Salve o documento resultante usando o método Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")
# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)
# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
section = doc2.Sections.get_Item(i)
# Loop through the child objects in the sections
for j in range(section.Body.ChildObjects.Count):
obj = section.Body.ChildObjects.get_Item(j)
# Add the child objects from the second document to the last section of the first document
lastSection.Body.ChildObjects.Add(obj.Clone())
# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Solicite uma licença temporária
Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
Python: объединить документы Word
Оглавление
Установить с помощью Пипа
pip install Spire.Doc
Ссылки по теме
Работа с большим количеством документов Word может быть очень сложной задачей. Будь то редактирование или просмотр большого количества документов, на открытие и закрытие документов тратится много времени. Более того, совместное использование и получение большого количества отдельных документов Word может раздражать, поскольку для этого может потребоваться множество повторяющихся операций отправки и получения как отправителем, так и получателем. Поэтому для повышения эффективности и экономии времени рекомендуется объединить связанные документы Word в один файл. Из этой статьи вы узнаете, как легко использовать Spire.Doc for Python объединить документы Word через программы Python.
- Объединение документов Word путем вставки файлов с помощью Python
- Объединение документов Word путем клонирования содержимого с помощью Python
Установите Spire.Doc for Python
Для этого сценария требуется Spire.Doc for Python и Plum-Dispatch v1.7.4. Их можно легко установить в ваш VS Code с помощью следующей команды pip.
pip install Spire.Doc
Если вы не знаете, как установить, обратитесь к этому руководству: Как установить Spire.Doc for Python в VS Code
Объединение документов Word путем вставки файлов с помощью Python
Метод Document.insertTextFromFile() используется для вставки других документов Word в текущий, при этом вставленное содержимое начинается с новой страницы. Подробные шаги по объединению документов Word путем вставки следующие:
- Создайте объект класса Document и загрузите документ Word с помощью метода Document.LoadFromFile().
- Вставьте в него содержимое из другого документа с помощью метода Document.InsertTextFromFile().
- Сохраните документ, используя метод Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")
# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)
# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Объединение документов Word путем клонирования содержимого с помощью Python
Объединение документов Word также может быть достигнуто путем клонирования содержимого одного документа Word в другой. Этот метод сохраняет форматирование исходного документа, а контент, клонированный из другого документа, продолжается в конце текущего документа, не начиная новую страницу. Подробные шаги следующие:
- Создайте два объекта класса Document и загрузите два документа Word с помощью метода Document.LoadFromFile().
- Получите последний раздел целевого документа, используя метод Document.Sections.get_Item().
- Прокрутите разделы документа, которые нужно клонировать, а затем просмотрите дочерние объекты разделов.
- Получите дочерний объект раздела, используя метод Раздел.Body.ChildObjects.get_Item().
- Добавьте дочерний объект в последний раздел целевого документа с помощью метода Раздел.Body.ChildObjects.Add().
- Сохраните полученный документ с помощью метода Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")
# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)
# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
section = doc2.Sections.get_Item(i)
# Loop through the child objects in the sections
for j in range(section.Body.ChildObjects.Count):
obj = section.Body.ChildObjects.get_Item(j)
# Add the child objects from the second document to the last section of the first document
lastSection.Body.ChildObjects.Add(obj.Clone())
# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
Python: Word-Dokumente zusammenführen
Inhaltsverzeichnis
Mit Pip installieren
pip install Spire.Doc
verwandte Links
Der Umgang mit einer großen Anzahl von Word-Dokumenten kann eine große Herausforderung sein. Unabhängig davon, ob es darum geht, eine große Anzahl von Dokumenten zu bearbeiten oder zu überprüfen, wird beim Öffnen und Schließen von Dokumenten viel Zeit verschwendet. Darüber hinaus kann das Teilen und Empfangen einer großen Anzahl separater Word-Dokumente lästig sein, da es viele wiederholte Sende- und Empfangsvorgänge sowohl seitens des Teilenden als auch des Empfängers erfordern kann. Um die Effizienz zu steigern und Zeit zu sparen, ist es daher ratsam, dies zu tun Zusammenführen zusammengehöriger Word-Dokumente in eine einzige Datei. In diesem Artikel erfahren Sie, wie Sie Spire.Doc for Python ganz einfach verwenden Word-Dokumente zusammenführen durch Python-Programme.
- Führen Sie Word-Dokumente zusammen, indem Sie Dateien mit Python einfügen
- Führen Sie Word-Dokumente zusammen, indem Sie Inhalte mit Python klonen
Installieren Sie Spire.Doc for Python
Dieses Szenario erfordert Spire.Doc for Python und plum-dispatch v1.7.4. Sie können mit dem folgenden pip-Befehl einfach in Ihrem VS-Code installiert werden.
pip install Spire.Doc
Wenn Sie sich bei der Installation nicht sicher sind, lesen Sie bitte dieses Tutorial: So installieren Sie Spire.Doc for Python in VS Code
Führen Sie Word-Dokumente zusammen, indem Sie Dateien mit Python einfügen
Die Methode Document.insertTextFromFile() wird verwendet, um andere Word-Dokumente in das aktuelle einzufügen, und der eingefügte Inhalt beginnt auf einer neuen Seite. Die detaillierten Schritte zum Zusammenführen von Word-Dokumenten durch Einfügen sind wie folgt:
- Erstellen Sie ein Objekt der Document-Klasse und laden Sie ein Word-Dokument mit der Methode Document.LoadFromFile().
- Fügen Sie den Inhalt eines anderen Dokuments mit der Methode Document.InsertTextFromFile() ein.
- Speichern Sie das Dokument mit der Methode Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")
# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)
# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Führen Sie Word-Dokumente zusammen, indem Sie Inhalte mit Python klonen
Das Zusammenführen von Word-Dokumenten kann auch durch das Klonen von Inhalten von einem Word-Dokument in ein anderes erreicht werden. Diese Methode behält die Formatierung des Originaldokuments bei und der aus einem anderen Dokument geklonte Inhalt wird am Ende des aktuellen Dokuments fortgesetzt, ohne eine neue Seite zu beginnen. Die detaillierten Schritte sind wie folgt:
- Erstellen Sie zwei Objekte der Document-Klasse und laden Sie zwei Word-Dokumente mit der Methode Document.LoadFromFile().
- Rufen Sie den letzten Abschnitt des Zieldokuments mit der Methode Document.Sections.get_Item() ab.
- Durchlaufen Sie die Abschnitte im Dokument, die geklont werden sollen, und durchlaufen Sie dann die untergeordneten Objekte der Abschnitte.
- Rufen Sie ein untergeordnetes Abschnittsobjekt mit der Methode Section.Body.ChildObjects.get_Item() ab.
- Fügen Sie das untergeordnete Objekt mit der Methode Section.Body.ChildObjects.Add() zum letzten Abschnitt des Zieldokuments hinzu.
- Speichern Sie das Ergebnisdokument mit der Methode Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")
# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)
# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
section = doc2.Sections.get_Item(i)
# Loop through the child objects in the sections
for j in range(section.Body.ChildObjects.Count):
obj = section.Body.ChildObjects.get_Item(j)
# Add the child objects from the second document to the last section of the first document
lastSection.Body.ChildObjects.Add(obj.Clone())
# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Beantragen Sie eine temporäre Lizenz
Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.
Python: fusionar documentos de Word
Tabla de contenido
Instalar con Pip
pip install Spire.Doc
enlaces relacionados
Manejar una gran cantidad de documentos de Word puede resultar un gran desafío. Ya sea editando o revisando una gran cantidad de documentos, se pierde mucho tiempo abriendo y cerrando documentos. Es más, compartir y recibir una gran cantidad de documentos de Word separados puede resultar molesto, ya que puede requerir muchas operaciones repetidas de envío y recepción tanto por parte del que comparte como del receptor. Por lo tanto, para mejorar la eficiencia y ahorrar tiempo, es aconsejable fusionar documentos de Word relacionados en un solo archivo. A partir de este artículo, sabrás cómo usar Spire.Doc for Python para fácilmente fusionar documentos de Word a través de programas Python.
- Fusionar documentos de Word insertando archivos con Python
- Fusionar documentos de Word clonando contenidos con Python
Instalar Spire.Doc for Python
Este escenario requiere Spire.Doc for Python y plum-dispatch v1.7.4. Se pueden instalar fácilmente en su código VS mediante el siguiente comando pip.
pip install Spire.Doc
Si no está seguro de cómo instalarlo, consulte este tutorial: Cómo instalar Spire.Doc for Python en VS Code
Fusionar documentos de Word insertando archivos con Python
El método Document.insertTextFromFile() se utiliza para insertar otros documentos de Word en el actual, y el contenido insertado comenzará desde una nueva página. Los pasos detallados para fusionar documentos de Word mediante inserción son los siguientes:
- Cree un objeto de la clase Documento y cargue un documento de Word usando el método Document.LoadFromFile().
- Inserte el contenido de otro documento utilizando el método Document.InsertTextFromFile().
- Guarde el documento utilizando el método Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create an object of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample1.docx")
# Insert the content from another Word document to this one
doc.InsertTextFromFile("Sample2.docx", FileFormat.Auto)
# Save the document
doc.SaveToFile("output/InsertDocuments.docx")
doc.Close()

Fusionar documentos de Word clonando contenidos con Python
También se puede fusionar documentos de Word clonando el contenido de un documento de Word a otro. Este método mantiene el formato del documento original y el contenido clonado de otro documento continúa al final del documento actual sin iniciar una nueva página. Los pasos detallados son los siguientes:
- Cree dos objetos de la clase Documento y cargue dos documentos de Word utilizando el método Document.LoadFromFile().
- Obtenga la última sección del documento de destino utilizando el método Document.Sections.get_Item().
- Recorra las secciones del documento que se van a clonar y luego recorra los objetos secundarios de las secciones.
- Obtenga un objeto secundario de sección utilizando el método Sección.Body.ChildObjects.get_Item().
- Agregue el objeto secundario a la última sección del documento de destino utilizando el método Sección.Body.ChildObjects.Add().
- Guarde el documento resultante utilizando el método Document.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create two objects of Document class and load two Word documents
doc1 = Document()
doc1.LoadFromFile("Sample1.docx")
doc2 = Document()
doc2.LoadFromFile("Sample2.docx")
# Get the last section of the first document
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)
# Loop through the sections in the second document
for i in range(doc2.Sections.Count):
section = doc2.Sections.get_Item(i)
# Loop through the child objects in the sections
for j in range(section.Body.ChildObjects.Count):
obj = section.Body.ChildObjects.get_Item(j)
# Add the child objects from the second document to the last section of the first document
lastSection.Body.ChildObjects.Add(obj.Clone())
# Save the result document
doc1.SaveToFile("output/MergeByCloning.docx")
doc1.Close()
doc2.Close()

Solicitar una licencia temporal
Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.