Python: convertir Word a PDF
Tabla de contenido
- Instalar Spire.Doc for Python
- Convertir Doc o Docx a PDF en Python
- Convierta Word a PDF protegido con contraseña en Python
- Convierta Word a PDF con marcadores en Python
- Convierta Word a PDF con fuentes integradas en Python
- Establecer la calidad de la imagen al convertir Word a PDF en Python
- Ver también
Instalar con Pip
pip install Spire.Doc
enlaces relacionados
Hoy en día, los documentos digitales juegan un papel importante en nuestra vida diaria, tanto en el ámbito personal como profesional. Uno de esos formatos comunes es Microsoft Word, que se utiliza para crear y editar documentos de texto. Sin embargo, puede llegar un momento en el que necesites convertir tus archivos de Word a un formato más accesible universalmente, como PDF. Los archivos PDF ofrecen ventajas como preservar el formato, garantizar la compatibilidad y mantener la integridad del documento en diferentes dispositivos y sistemas operativos. En este artículo, aprenderá cómo convertir Word a PDF en Python usando Spire.Doc for Python.
- Convertir Doc o Docx a PDF en Python
- Convierta Word a PDF protegido con contraseña en Python
- Convierta Word a PDF con marcadores en Python
- Convierta Word a PDF con fuentes integradas en Python
- Establecer la calidad de la imagen al convertir Word a PDF en 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
Convertir Doc o Docx a PDF en Python
Spire.Doc for Python ofrece el método Document.SaveToFile(string fileName, FileFormat fileFormat) que permite guardar Word como PDF, XPS, HTML, RTF, etc. Si solo desea guardar sus documentos de Word como PDF normales sin configuraciones adicionales, siga los pasos a continuación.
- Crea un objeto de documento.
- Cargue un documento de Word de muestra utilizando el método Document.LoadFromFile().
- Guarde el documento en PDF utilizando el método Doucment.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create word document
document = Document()
# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Convierta Word a PDF protegido con contraseña en Python
Para convertir Word a un PDF protegido con contraseña, puede utilizar el método Document.SaveToFile(string fileName, ToPdfParameterList paramList), donde el parámetro ToPdfParameterList le permite controlar el proceso de conversión de un documento de Word a un formato PDF. Esto incluye opciones como cifrar el documento durante la conversión. Estos son los pasos específicos para realizar esta tarea.
- Crea un objeto de documento.
- Cargue un documento de Word de muestra utilizando el método Document.LoadFromFile().
- Cree un objeto ToPdfParameterList, que se utiliza para configurar las opciones de conversión.
- Especifique la contraseña de apertura y la contraseña de permiso y luego configure ambas contraseñas para el PDF generado utilizando el método ToPdfParameterList.PdfSecurity.Encrypt().
- Guarde el documento de Word en PDF con contraseña utilizando el método Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"
# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)
# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Convierta Word a PDF con marcadores en Python
Agregar marcadores a un documento puede mejorar su legibilidad. Al crear un PDF desde Word, es posible que desee conservar los marcadores existentes o crear otros nuevos basados en los títulos. Estos son los pasos para convertir Word a PDF manteniendo los marcadores.
- Crea un objeto de documento.
- Cargue un archivo de Word usando el método Document.LoadFromFile().
- Cree un objeto ToPdfParameterList, que se utiliza para configurar las opciones de conversión.
- Cree marcadores en PDF a partir de los encabezados en Word configurando ToPdfParameterList.CreateWordBookmarksUsingHeadings en verdadero.
- Guarde el documento en PDF con marcadores utilizando el método Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parames = ToPdfParameterList()
# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True
# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True
# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Convierta Word a PDF con fuentes integradas en Python
Para garantizar una apariencia uniforme de un documento PDF en cualquier dispositivo, probablemente necesite incrustar fuentes en el documento PDF generado. Los siguientes son los pasos para incrustar las fuentes utilizadas en un documento de Word en el PDF resultante.
- Crea un objeto de documento.
- Cargue un archivo de Word de muestra utilizando el método Document.LoadFromFile().
- Cree un objeto ToPdfParameterList, que se utiliza para configurar las opciones de conversión.
- Incruste fuentes en el PDF generado a través de la propiedad ToPdfParameterList.IsEmbeddedAllFonts.
- Guarde el documento en PDF utilizando el método Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True
# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Establecer la calidad de la imagen al convertir Word a PDF en Python
Al convertir un documento de Word a PDF, es importante considerar el tamaño del archivo resultante, especialmente si contiene numerosas imágenes de alta calidad. Tiene la opción de comprimir la calidad de la imagen durante el proceso de conversión. Para hacer esto, siga los pasos a continuación.
- Crea un objeto de documento.
- Cargue un archivo de Word de muestra utilizando el método Document.LoadFromFile().
- Establezca la calidad de la imagen a través de la propiedad Document.JPEGQuality.
- Guarde el documento en PDF utilizando el método Doucment.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Compress image to 40% of its original quality
document.JPEGQuality = 40
# Preserve original image quality
# document.JPEGQuality = 100
# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.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.
Python: Word를 PDF로 변환
오늘날 디지털 문서는 개인적 환경과 직업적 환경 모두에서 일상 생활에서 중요한 역할을 합니다. 이러한 일반적인 형식 중 하나는 텍스트 문서를 작성하고 편집하는 데 사용되는 Microsoft Word입니다. 그러나 Word 파일을 PDF와 같이 보다 보편적으로 액세스할 수 있는 형식으로 변환해야 할 때가 있을 수 있습니다. PDF는 서식 유지, 호환성 보장, 다양한 장치 및 운영 체제 전반에서 문서 무결성 유지와 같은 이점을 제공합니다. 이 기사에서는 다음 방법을 배웁니다 Python에서 Word를 PDF로 변환 Spire.Doc for Python사용합니다.
- Python에서 Doc 또는 Docx를 PDF로 변환
- Python에서 Word를 비밀번호로 보호된 PDF로 변환
- Python의 책갈피를 사용하여 Word를 PDF로 변환
- Python에 포함된 글꼴을 사용하여 Word를 PDF로 변환
- Python에서 Word를 PDF로 변환할 때 이미지 품질 설정
Spire.Doc for Python 설치
이 시나리오에는 Spire.Doc for Python 및 Plum-dispatch v1.7.4가 필요합니다. 다음 pip 명령을 통해 VS Code에 쉽게 설치할 수 있습니다.
pip install Spire.Doc
설치 방법을 잘 모르는 경우 다음 튜토리얼을 참조하세요: VS Code에서 Spire.Doc for Python를 설치하는 방법
Python에서 Doc 또는 Docx를 PDF로 변환
Spire.Doc for Python Word를 PDF, XPS, HTML, RTF 등으로 저장할 수 있는 Document.SaveToFile(string fileName, FileFormat fileFormat) 메서드를 제공합니다. 추가 설정 없이 Word 문서를 일반 PDF로 저장하고 싶다면, 아래 단계를 따르십시오.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
- Doucment.SaveToFile() 메서드를 사용하여 문서를 PDF로 저장합니다.
- Python
from spire.doc import *
from spire.doc.common import *
# Create word document
document = Document()
# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Python에서 Word를 비밀번호로 보호된 PDF로 변환
Word를 암호로 보호된 PDF로 변환하려면 Document.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 활용할 수 있습니다. 여기서 ToPdfParameterList 매개 변수를 사용하면 Word 문서를 PDF 형식으로 변환하는 과정을 제어할 수 있습니다. 여기에는 변환 중 문서 암호화와 같은 옵션이 포함됩니다. 이 작업을 수행하기 위한 구체적인 단계는 다음과 같습니다.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 샘플 Word 문서를 로드합니다.
- 변환 옵션을 설정하는 데 사용되는 ToPdfParameterList 개체를 만듭니다.
- 열기 암호와 권한 암호를 지정한 다음 ToPdfParameterList.PdfSecurity.Encrypt() 메서드를 사용하여 생성된 PDF에 대해 두 암호를 모두 설정합니다.
- Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 사용하여 Word 문서를 비밀번호로 PDF에 저장합니다.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"
# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)
# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Python의 책갈피를 사용하여 Word를 PDF로 변환
문서에 책갈피를 추가하면 가독성이 향상될 수 있습니다. Word에서 PDF를 만들 때 기존 책갈피를 유지하거나 제목을 기반으로 새 책갈피를 만들고 싶을 수 있습니다. 책갈피를 유지하면서 Word를 PDF로 변환하는 단계는 다음과 같습니다.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 Word 파일을 로드합니다.
- 변환 옵션을 설정하는 데 사용되는 ToPdfParameterList 개체를 만듭니다.
- ToPdfParameterList.CreateWordBookmarksUsingHeadings를 true로 설정하여 Word의 제목에서 PDF의 책갈피를 만듭니다.
- Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 사용하여 책갈피를 사용하여 문서를 PDF에 저장합니다.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parames = ToPdfParameterList()
# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True
# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True
# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Python에 포함된 글꼴을 사용하여 Word를 PDF로 변환
모든 장치에서 PDF 문서의 일관된 모양을 보장하려면 생성된 PDF 문서에 글꼴을 포함해야 할 수도 있습니다. 다음은 Word 문서에 사용된 글꼴을 결과 PDF에 포함시키는 단계입니다.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 샘플 Word 파일을 로드합니다.
- 변환 옵션을 설정하는 데 사용되는 ToPdfParameterList 개체를 만듭니다.
- ToPdfParameterList.IsEmbeddedAllFonts 속성을 통해 생성된 PDF에 글꼴을 포함합니다.
- Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) 메서드를 사용하여 문서를 PDF에 저장합니다.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True
# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Python에서 Word를 PDF로 변환할 때 이미지 품질 설정
Word 문서를 PDF로 변환할 때, 특히 고품질 이미지가 많이 포함된 경우 결과 파일의 크기를 고려하는 것이 중요합니다. 변환 프로세스 중에 이미지 품질을 압축할 수 있는 옵션이 있습니다. 이렇게 하려면 아래 단계를 따르세요.
- 문서 개체를 만듭니다.
- Document.LoadFromFile() 메서드를 사용하여 샘플 Word 파일을 로드합니다.
- Document.JPEGQuality 속성을 통해 이미지 품질을 설정합니다.
- Doucment.SaveToFile() 메서드를 사용하여 문서를 PDF로 저장합니다.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Compress image to 40% of its original quality
document.JPEGQuality = 40
# Preserve original image quality
# document.JPEGQuality = 100
# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()
임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
Python: converti Word in PDF
Sommario
- Installa Spire.Doc for Python
- Converti Doc o Docx in PDF in Python
- Converti Word in PDF protetto da password in Python
- Converti Word in PDF con i segnalibri in Python
- Converti Word in PDF con caratteri incorporati in Python
- Imposta la qualità dell'immagine durante la conversione di Word in PDF in Python
- Guarda anche
Installa con Pip
pip install Spire.Doc
Link correlati
Al giorno d'oggi, i documenti digitali svolgono un ruolo significativo nella nostra vita quotidiana, sia in ambito personale che professionale. Uno di questi formati comuni è Microsoft Word, utilizzato per creare e modificare documenti di testo. Tuttavia, potrebbe arrivare il momento in cui sarà necessario convertire i file Word in un formato più universalmente accessibile, come PDF. I PDF offrono vantaggi come preservare la formattazione, garantire la compatibilità e mantenere l'integrità del documento su diversi dispositivi e sistemi operativi. In questo articolo imparerai come farlo convertire Word in PDF in Python utilizzando Spire.Doc for Python.
- Converti Doc o Docx in PDF in Python
- Converti Word in PDF protetto da password in Python
- Converti Word in PDF con i segnalibri in Python
- Converti Word in PDF con caratteri incorporati in Python
- Imposta la qualità dell'immagine durante la conversione di Word in PDF in Python
Installa Spire.Doc for Python
Questo scenario richiede Spire.Doc for Python e plum-dispatch v1.7.4. Possono essere facilmente installati nel tuo VS Code tramite il seguente comando pip.
pip install Spire.Doc
Se non sei sicuro su come installare, fai riferimento a questo tutorial: Come installare Spire.Doc for Python in VS Code
Converti Doc o Docx in PDF in Python
Spire.Doc for Python offre il metodo Document.SaveToFile(string fileName, FileFormat fileFormat) che consente di salvare Word come PDF, XPS, HTML, RTF, ecc. Se desideri semplicemente salvare i tuoi documenti Word come normali PDF senza impostazioni aggiuntive, seguire i passaggi seguenti.
- Creare un oggetto Documento.
- Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
- Salva il documento in PDF utilizzando il metodo Doucment.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create word document
document = Document()
# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Converti Word in PDF protetto da password in Python
Per convertire Word in un PDF protetto da password, è possibile utilizzare il metodo Document.SaveToFile(string fileName, ToPdfParameterList paramList), dove il parametro ToPdfParameterList consente di controllare il processo di conversione di un documento Word in un formato PDF. Ciò include opzioni come la crittografia del documento durante la conversione. Ecco i passaggi specifici per eseguire questa attività.
- Creare un oggetto Documento.
- Carica un documento Word di esempio utilizzando il metodo Document.LoadFromFile().
- Creare un oggetto ToPdfParameterList, utilizzato per impostare le opzioni di conversione.
- Specificare la password di apertura e la password di autorizzazione, quindi impostare entrambe le password per il PDF generato utilizzando il metodo ToPdfParameterList.PdfSecurity.Encrypt().
- Salva il documento Word in PDF con password utilizzando il metodo Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"
# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)
# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Converti Word in PDF con i segnalibri in Python
L'aggiunta di segnalibri a un documento può migliorarne la leggibilità. Quando crei un PDF da Word, potresti voler mantenere i segnalibri esistenti o crearne di nuovi in base ai titoli. Ecco i passaggi per convertire Word in PDF mantenendo i segnalibri.
- Creare un oggetto Documento.
- Carica un file Word utilizzando il metodo Document.LoadFromFile().
- Creare un oggetto ToPdfParameterList, utilizzato per impostare le opzioni di conversione.
- Crea segnalibri in PDF dalle intestazioni in Word impostando ToPdfParameterList.CreateWordBookmarksUsingHeadings su true.
- Salvare il documento in PDF con i segnalibri utilizzando il metodo Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parames = ToPdfParameterList()
# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True
# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True
# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Converti Word in PDF con caratteri incorporati in Python
Per garantire un aspetto coerente di un documento PDF su qualsiasi dispositivo, probabilmente dovrai incorporare i caratteri nel documento PDF generato. Di seguito sono riportati i passaggi per incorporare i caratteri utilizzati in un documento Word nel PDF risultante.
- Creare un oggetto Documento.
- Carica un file Word di esempio utilizzando il metodo Document.LoadFromFile().
- Creare un oggetto ToPdfParameterList, utilizzato per impostare le opzioni di conversione.
- Incorpora i caratteri nel PDF generato tramite la proprietà ToPdfParameterList.IsEmbeddedAllFonts.
- Salvare il documento in PDF utilizzando il metodo Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True
# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Imposta la qualità dell'immagine durante la conversione di Word in PDF in Python
Quando si converte un documento Word in PDF, è importante considerare la dimensione del file risultante, soprattutto se contiene numerose immagini di alta qualità. Hai la possibilità di comprimere la qualità dell'immagine durante il processo di conversione. Per fare ciò, seguire i passaggi seguenti.
- Creare un oggetto Documento.
- Carica un file Word di esempio utilizzando il metodo Document.LoadFromFile().
- Imposta la qualità dell'immagine tramite la proprietà Document.JPEGQuality.
- Salva il documento in PDF utilizzando il metodo Doucment.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Compress image to 40% of its original quality
document.JPEGQuality = 40
# Preserve original image quality
# document.JPEGQuality = 100
# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()
Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
Python : convertir Word en PDF
Table des matières
- Installer Spire.Doc for Python
- Convertir Doc ou Docx en PDF en Python
- Convertir Word en PDF protégé par mot de passe en Python
- Convertir Word en PDF avec des signets en Python
- Convertir Word en PDF avec des polices intégrées dans Python
- Définir la qualité de l'image lors de la conversion de Word en PDF en Python
- Voir également
Installer avec Pip
pip install Spire.Doc
Liens connexes
De nos jours, les documents numériques jouent un rôle important dans notre vie quotidienne, tant dans le cadre personnel que professionnel. L'un de ces formats courants est Microsoft Word, utilisé pour créer et éditer des documents textuels. Cependant, il peut arriver un moment où vous devrez convertir vos fichiers Word dans un format plus universellement accessible, tel que PDF. Les PDF offrent des avantages tels que la préservation du formatage, la garantie de la compatibilité et le maintien de l'intégrité des documents sur différents appareils et systèmes d'exploitation. Dans cet article, vous apprendrez comment convertir Word en PDF en Python en utilisant Spire.Doc for Python.
- Convertir Doc ou Docx en PDF en Python
- Convertir Word en PDF protégé par mot de passe en Python
- Convertir Word en PDF avec des signets en Python
- Convertir Word en PDF avec des polices intégrées dans Python
- Définir la qualité de l'image lors de la conversion de Word en PDF en Python
Installer Spire.Doc for Python
Ce scénario nécessite Spire.Doc for Python et plum-dispatch v1.7.4. Ils peuvent être facilement installés dans votre VS Code via la commande pip suivante.
pip install Spire.Doc
Si vous ne savez pas comment procéder à l'installation, veuillez vous référer à ce didacticiel : Comment installer Spire.Doc for Python dans VS Code
Convertir Doc ou Docx en PDF en Python
Spire.Doc for Python propose la méthode Document.SaveToFile(string fileName, FileFormat fileFormat) qui permet d'enregistrer Word au format PDF, XPS, HTML, RTF, etc. Si vous souhaitez simplement enregistrer vos documents Word au format PDF standard sans paramètres supplémentaires, suivez les étapes ci-dessous.
- Créez un objet Document.
- Chargez un exemple de document Word à l’aide de la méthode Document.LoadFromFile().
- Enregistrez le document au format PDF à l'aide de la méthode Doucment.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create word document
document = Document()
# Load a doc or docx file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
#Save the document to PDF
document.SaveToFile("output/ToPDF.pdf", FileFormat.PDF)
document.Close()

Convertir Word en PDF protégé par mot de passe en Python
Pour convertir Word en PDF protégé par mot de passe, vous pouvez utiliser la méthode Document.SaveToFile(string fileName, ToPdfParameterList paramList), où le paramètre ToPdfParameterList vous permet de contrôler le processus de conversion d'un document Word au format PDF. Cela inclut des options telles que le cryptage du document lors de la conversion. Voici les étapes spécifiques pour accomplir cette tâche.
- Créez un objet Document.
- Chargez un exemple de document Word à l’aide de la méthode Document.LoadFromFile().
- Créez un objet ToPdfParameterList, utilisé pour définir les options de conversion.
- Spécifiez le mot de passe d'ouverture et le mot de passe d'autorisation, puis définissez les deux mots de passe pour le PDF généré à l'aide de la méthode ToPdfParameterList.PdfSecurity.Encrypt().
- Enregistrez le document Word au format PDF avec un mot de passe à l'aide de la méthode Doucment.SaveToFile (string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Specify open password and permission password
openPsd = "abc-123"
permissionPsd = "permission"
# Protect the PDF to be generated with open password and permission password
parameter.PdfSecurity.Encrypt(openPsd, permissionPsd, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit)
# Save the Word document to PDF
document.SaveToFile("output/ToPdfWithPassword.pdf", parameter)
document.Close()

Convertir Word en PDF avec des signets en Python
L'ajout de signets à un document peut améliorer sa lisibilité. Lors de la création d'un PDF à partir de Word, vous souhaiterez peut-être conserver les signets existants ou en créer de nouveaux en fonction des titres. Voici les étapes pour convertir Word en PDF tout en conservant les signets.
- Créez un objet Document.
- Chargez un fichier Word à l'aide de la méthode Document.LoadFromFile().
- Créez un objet ToPdfParameterList, utilisé pour définir les options de conversion.
- Créez des signets au format PDF à partir des titres dans Word en définissant ToPdfParameterList.CreateWordBookmarksUsingHeadings sur true.
- Enregistrez le document au format PDF avec des signets à l'aide de la méthode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parames = ToPdfParameterList()
# Create bookmarks from Word headings
parames.CreateWordBookmarksUsingHeadings = True
# Create bookmarks in PDF from existing bookmarks in Word
# parames.CreateWordBookmarks = True
# Save the document to PDF
document.SaveToFile("output/ToPdfWithBookmarks.pdf", FileFormat.PDF)
document.Close()

Convertir Word en PDF avec des polices intégrées dans Python
Pour garantir une apparence cohérente d'un document PDF sur n'importe quel appareil, vous devrez probablement intégrer des polices dans le document PDF généré. Voici les étapes pour intégrer les polices utilisées dans un document Word dans le PDF résultant.
- Créez un objet Document.
- Chargez un exemple de fichier Word à l’aide de la méthode Document.LoadFromFile().
- Créez un objet ToPdfParameterList, utilisé pour définir les options de conversion.
- Incorporez les polices dans le PDF généré via la propriété ToPdfParameterList.IsEmbeddedAllFonts.
- Enregistrez le document au format PDF à l'aide de la méthode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Create a ToPdfParameterList object
parameter = ToPdfParameterList()
# Embed fonts in PDF
parameter.IsEmbeddedAllFonts = True
# Save the Word document to PDF
document.SaveToFile("output/EmbedFonts.pdf", parameter)
document.Close()

Définir la qualité de l'image lors de la conversion de Word en PDF en Python
Lors de la conversion d'un document Word en PDF, il est important de prendre en compte la taille du fichier résultant, surtout s'il contient de nombreuses images de haute qualité. Vous avez la possibilité de compresser la qualité de l'image pendant le processus de conversion. Pour faire ça, suit les étapes suivantes.
- Créez un objet Document.
- Chargez un exemple de fichier Word à l’aide de la méthode Document.LoadFromFile().
- Définissez la qualité de l’image via la propriété Document.JPEGQuality.
- Enregistrez le document au format PDF à l'aide de la méthode Doucment.SaveToFile().
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx")
# Compress image to 40% of its original quality
document.JPEGQuality = 40
# Preserve original image quality
# document.JPEGQuality = 100
# Save the Word document to PDF
document.SaveToFile("output/SetImageQuality.pdf", FileFormat.PDF)
document.Close()
Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
Java: Create, Read, or Update Excel Documents
Table of Contents
Install with Maven
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>14.1.3</version>
</dependency>
Related Links
The Excel spreadsheet is a popular file format that allows users to arrange, analyze, and display data in tables. The ability to programmatically interact with Excel files is valuable for automating and integrating its features into software. This is especially beneficial when dealing with extensive datasets, complex calculations, or dynamically generating/updating data. In this article, you will learn how to create, read, or update Excel document in Java using Spire.XLS for Java.
Install Spire.XLS for Java
First, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>16.2.6</version>
</dependency>
</dependencies>
Create an Excel Document in Java
Spire.XLS for Java offers a variety of classes and interfaces that you can use to create and edit Excel documents. Here is a list of important classes, properties and methods involved in this article.
| Member | Description |
| Workbook class | Represents an Excel workbook model. |
| Workbook.getWorksheets().add() method | Adds a worksheet to workbook. |
| Workbook.saveToFile() method | Saves the workbook to an Excel document. |
| Worksheet class | Represents a worksheet in a workbook. |
| Worksheet.getRange() method | Gets a specific cell or cell range from worksheet. |
| Worksheet.insertArray() method | Imports data from an array to worksheet. |
| CellRange class | Represents a cell or cell range in worksheet. |
| CellRange.setValue() method | Sets the value of a cell. |
| CellRange.getValue() method | Gets the value of a cell. |
The following are the steps to create an Excel document from scratch using Spire.XLS for Java.
- Create a Workbook object.
- Add a worksheet using Workbook.getWorksheets().add() method.
- Write data to a specific cell using Worksheet.getRange.setValue() method.
- Import data from an array to the worksheet using Worksheet.insertArray() method.
- Save the workbook to an Excel document using Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
public class CreateSpreadsheet {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Remove default worksheets
wb.getWorksheets().clear();
//Add a worksheet and name it "Employee"
Worksheet sheet = wb.getWorksheets().add("Employee");
//Merge the cells between A1 and G1
sheet.getRange().get("A1:G1").merge();
//Write data to A1 and apply formatting to it
sheet.getRange().get("A1").setValue("Basic Information of Employees of Huanyu Automobile Company");
sheet.getRange().get("A1").setHorizontalAlignment(HorizontalAlignType.Center);
sheet.getRange().get("A1").setVerticalAlignment(VerticalAlignType.Center);
sheet.getRange().get("A1").getStyle().getFont().isBold(true);
sheet.getRange().get("A1").getStyle().getFont().setSize(13);
//Set row height of the first row
sheet.setRowHeight(1,30);
//Create a two-dimensional array
String[][] twoDimensionalArray = new String[][]{
{"Name", "Gender", "Birth Date", "Educational Background", "Contact Number", "Position", "ID"},
{"Allen", "Male", "1990-02-10", "Bachelor", "24756854", "Mechanic", "0021"},
{"Patrick", "Male", "1985-06-08", "Master", "59863247", "Mechanic", "0022"},
{"Jenna", "Female", "1989-11-25", "Bachelor", "79540352", "Sales", "0023"},
{"Tommy", "Male", "1988-04-16", "Master", "52014060", "Mechanic", "0024"},
{"Christina", "Female", "1998-01-21", "Bachelor", "35401489", "HR", "0025"}
};
//Import data from DataTable to worksheet
sheet.insertArray(twoDimensionalArray,2,1);
//Set row height of a range
sheet.getRange().get("A2:G7").setRowHeight(15);
//Set column width
sheet.setColumnWidth(2,15);
sheet.setColumnWidth(3,21);
sheet.setColumnWidth(4,15);
//Set border style of a range
sheet.getRange().get("A2:G7").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").borderInside(LineStyleType.Thin);
sheet.getRange().get("A2:G2").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").getBorders().setKnownColor(ExcelColors.Black);
//Save to a .xlsx file
wb.saveToFile("output/NewSpreadsheet.xlsx", FileFormat.Version2016);
}
}

Read Data of a Worksheet in Java
The CellRange.getValue() method returns number value or text value of a cell as a string. To get data of a whole worksheet or a cell range, loop through the cells within it. The following are the steps to get data of a worksheet using Spire.XLS for Java.
- Create a Workbook object.
- Load an Excel document using Workbook.loadFromFile() method.
- Get a specific worksheet using Workbook.getWorksheets().get(index) method.
- Get the cell range containing data using Worksheet.getAllocatedRange() method.
- Iterate through the rows and columns to get cells within the range, and return the value of each cell using CellRange.getValue() method.
- Java
import com.spire.xls.CellRange;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReadData {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Get the cell range containing data
CellRange locatedRange = sheet.getAllocatedRange();
//Iterate through the rows
for (int i = 0; i < locatedRange.getRows().length; i++) {
//Iterate through the columns
for (int j = 0; j < locatedRange.getColumnCount(); j++) {
//Get data of a specific cell
System.out.print(locatedRange.get(i + 1, j + 1).getValue() + " ");
}
System.out.println();
}
}
}

Update an Excel Document in Java
To change the value of a certain cell, just re-assign a value to it using Worksheet.getRange().setValue() method. The following are the detailed steps.
- Create a Workbook object.
- Load an Excel document using Workbook.LoadFromFile() method.
- Get a specific worksheet through Workbook.Worksheets[index] property.
- Change the value of a particular cell though Worksheet.Range.Value property.
- Save the workbook to an Excel file using Workbook.SaveToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class UpdateExcel {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Change the value of a specific cell
sheet.getRange().get("A1").setValue("Updated Value");
//Save to file
wb.saveToFile("output/Updated.xlsx", ExcelVersion.Version2016);
}
}

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.
Java: crie, leia ou atualize documentos Excel
Índice
Instalar com Maven
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>14.1.3</version>
</dependency>
Links Relacionados
A planilha do Excel é um formato de arquivo popular que permite aos usuários organizar, analisar e exibir dados em tabelas. A capacidade de interagir programaticamente com arquivos do Excel é valiosa para automatizar e integrar seus recursos ao software. Isso é especialmente benéfico ao lidar com conjuntos de dados extensos, cálculos complexos ou geração/atualização dinâmica de dados. Neste artigo você aprenderá como crie, leia ou atualize documentos Excel em Java usando Spire.XLS for Java.
- Crie um documento Excel em Java
- Ler dados de uma planilha em Java
- Atualizar um documento Excel em Java
Instale Spire.XLS for Java
Primeiro, é necessário adicionar o arquivo Spire.Xls.jar como uma dependência em seu programa Java. O arquivo JAR pode ser baixado neste link. Se você usa Maven, pode importar facilmente o arquivo JAR em seu aplicativo adicionando o código a seguir ao arquivo pom.xml do seu projeto.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>16.2.6</version>
</dependency>
</dependencies>
Crie um documento Excel em Java
Spire.XLS for Java oferece uma variedade de classes e interfaces que você pode usar para criar e editar documentos Excel. Aqui está uma lista de classes, propriedades e métodos importantes envolvidos neste artigo.
| Membro | Descrição |
| Aula de apostila | Representa um modelo de pasta de trabalho do Excel. |
| Método Workbook.getWorksheets().add() | Adiciona uma planilha à pasta de trabalho. |
| Método Workbook.saveToFile() | Salva a pasta de trabalho em um documento Excel. |
| Aula de planilha | Representa uma planilha em uma pasta de trabalho. |
| Método Worksheet.getRange() | Obtém uma célula ou intervalo de células específico da planilha. |
| Método Worksheet.insertArray() | Importa dados de uma matriz para uma planilha. |
| Classe CellRange | Representa uma célula ou intervalo de células na planilha. |
| Método CellRange.setValue() | Define o valor de uma célula. |
| Método CellRange.getValue() | Obtém o valor de uma célula. |
A seguir estão as etapas para criar um documento Excel do zero usando Spire.XLS for Java.
- Crie um objeto Pasta de trabalho.
- Adicione uma planilha usando o método Workbook.getWorksheets().add().
- Grave dados em uma célula específica usando o método Worksheet.getRange.setValue().
- Importe dados de um array para a planilha usando o método Worksheet.insertArray().
- Salve a pasta de trabalho em um documento Excel usando o método Workbook.saveToFile().
- Java
import com.spire.xls.*;
public class CreateSpreadsheet {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Remove default worksheets
wb.getWorksheets().clear();
//Add a worksheet and name it "Employee"
Worksheet sheet = wb.getWorksheets().add("Employee");
//Merge the cells between A1 and G1
sheet.getRange().get("A1:G1").merge();
//Write data to A1 and apply formatting to it
sheet.getRange().get("A1").setValue("Basic Information of Employees of Huanyu Automobile Company");
sheet.getRange().get("A1").setHorizontalAlignment(HorizontalAlignType.Center);
sheet.getRange().get("A1").setVerticalAlignment(VerticalAlignType.Center);
sheet.getRange().get("A1").getStyle().getFont().isBold(true);
sheet.getRange().get("A1").getStyle().getFont().setSize(13);
//Set row height of the first row
sheet.setRowHeight(1,30);
//Create a two-dimensional array
String[][] twoDimensionalArray = new String[][]{
{"Name", "Gender", "Birth Date", "Educational Background", "Contact Number", "Position", "ID"},
{"Allen", "Male", "1990-02-10", "Bachelor", "24756854", "Mechanic", "0021"},
{"Patrick", "Male", "1985-06-08", "Master", "59863247", "Mechanic", "0022"},
{"Jenna", "Female", "1989-11-25", "Bachelor", "79540352", "Sales", "0023"},
{"Tommy", "Male", "1988-04-16", "Master", "52014060", "Mechanic", "0024"},
{"Christina", "Female", "1998-01-21", "Bachelor", "35401489", "HR", "0025"}
};
//Import data from DataTable to worksheet
sheet.insertArray(twoDimensionalArray,2,1);
//Set row height of a range
sheet.getRange().get("A2:G7").setRowHeight(15);
//Set column width
sheet.setColumnWidth(2,15);
sheet.setColumnWidth(3,21);
sheet.setColumnWidth(4,15);
//Set border style of a range
sheet.getRange().get("A2:G7").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").borderInside(LineStyleType.Thin);
sheet.getRange().get("A2:G2").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").getBorders().setKnownColor(ExcelColors.Black);
//Save to a .xlsx file
wb.saveToFile("output/NewSpreadsheet.xlsx", FileFormat.Version2016);
}
}

Ler dados de uma planilha em Java
O método CellRange.getValue() retorna o valor numérico ou o valor do texto de uma célula como uma string. Para obter dados de uma planilha inteira ou de um intervalo de células, percorra as células dentro dela. A seguir estão as etapas para obter dados de uma planilha usando Spire.XLS for Java.
- Crie um objeto Pasta de trabalho.
- Carregue um documento Excel usando o método Workbook.loadFromFile().
- Obtenha uma planilha específica usando o método Workbook.getWorksheets().get(index).
- Obtenha o intervalo de células contendo dados usando o método Worksheet.getAllocatedRange().
- Itere pelas linhas e colunas para obter células dentro do intervalo e retorne o valor de cada célula usando o método CellRange.getValue().
- Java
import com.spire.xls.CellRange;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReadData {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Get the cell range containing data
CellRange locatedRange = sheet.getAllocatedRange();
//Iterate through the rows
for (int i = 0; i < locatedRange.getRows().length; i++) {
//Iterate through the columns
for (int j = 0; j < locatedRange.getColumnCount(); j++) {
//Get data of a specific cell
System.out.print(locatedRange.get(i + 1, j + 1).getValue() + " ");
}
System.out.println();
}
}
}

Atualizar um documento Excel em Java
Para alterar o valor de uma determinada célula, basta reatribuir um valor a ela usando o método Worksheet.getRange().setValue(). A seguir estão as etapas detalhadas.
- Crie um objeto Pasta de trabalho.
- Carregue um documento Excel usando o método Workbook.LoadFromFile().
- Obtenha uma planilha específica por meio da propriedade Workbook.Worksheets[index].
- Altere o valor de uma célula específica por meio da propriedade Worksheet.Range.Value.
- Salve a pasta de trabalho em um arquivo Excel usando o método Workbook.SaveToFile().
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class UpdateExcel {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Change the value of a specific cell
sheet.getRange().get("A1").setValue("Updated Value");
//Save to file
wb.saveToFile("output/Updated.xlsx", ExcelVersion.Version2016);
}
}

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.
Java: создание, чтение или обновление документов Excel
Оглавление
Установка с помощью Maven
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>14.1.3</version>
</dependency>
Ссылки по теме
Электронная таблица Excel — это популярный формат файлов, который позволяет пользователям упорядочивать, анализировать и отображать данные в таблицах. Возможность программного взаимодействия с файлами Excel полезна для автоматизации и интеграции его функций в программное обеспечение. Это особенно полезно при работе с обширными наборами данных, сложными вычислениями или динамическим созданием/обновлением данных. В этой статье вы узнаете, как создавайте, читайте или обновляйте документ Excel на Java помощью Spire.XLS for Java.
- Создать документ Excel на Java
- Чтение данных рабочего листа в Java
- Обновление документа Excel в Java
Установите Spire.XLS for Java
Во-первых, вам необходимо добавить файл Spire.Xls.jar в качестве зависимости в вашу программу Java. JAR-файл можно скачать по этой ссылке. Если вы используете Maven, вы можете легко импортировать файл JAR в свое приложение, добавив следующий код в файл pom.xml вашего проекта.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>16.2.6</version>
</dependency>
</dependencies>
Создать документ Excel на Java
Spire.XLS for Java предлагает множество классов и интерфейсов, которые можно использовать для создания и редактирования документов Excel. Вот список важных классов, свойств и методов, рассматриваемых в этой статье.
| Член | Описание |
| Класс рабочей книги | Представляет модель книги Excel. |
| Метод Workbook.getWorksheets().add() | Добавляет лист в книгу. |
| Метод Workbook.saveToFile() | Сохраняет книгу в документ Excel. |
| Класс рабочего листа | Представляет лист в книге. |
| Метод Worksheet.getRange() | Получает определенную ячейку или диапазон ячеек из листа. |
| Метод Worksheet.insertArray() | Импортирует данные из массива на лист. |
| Класс CellRange | Представляет ячейку или диапазон ячеек на листе. |
| Метод CellRange.setValue() | Устанавливает значение ячейки. |
| Метод CellRange.getValue() | Получает значение ячейки. |
Ниже приведены шаги по созданию документа Excel с нуля с помощью Spire.XLS for Java.
- Создайте объект книги.
- Добавьте рабочий лист, используя метод Workbook.getWorksheets().add().
- Запишите данные в определенную ячейку с помощью метода Worksheet.getRange.setValue().
- Импортируйте данные из массива на лист с помощью метода Worksheet.insertArray().
- Сохраните книгу в документ Excel, используя метод Workbook.saveToFile().
- Java
import com.spire.xls.*;
public class CreateSpreadsheet {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Remove default worksheets
wb.getWorksheets().clear();
//Add a worksheet and name it "Employee"
Worksheet sheet = wb.getWorksheets().add("Employee");
//Merge the cells between A1 and G1
sheet.getRange().get("A1:G1").merge();
//Write data to A1 and apply formatting to it
sheet.getRange().get("A1").setValue("Basic Information of Employees of Huanyu Automobile Company");
sheet.getRange().get("A1").setHorizontalAlignment(HorizontalAlignType.Center);
sheet.getRange().get("A1").setVerticalAlignment(VerticalAlignType.Center);
sheet.getRange().get("A1").getStyle().getFont().isBold(true);
sheet.getRange().get("A1").getStyle().getFont().setSize(13);
//Set row height of the first row
sheet.setRowHeight(1,30);
//Create a two-dimensional array
String[][] twoDimensionalArray = new String[][]{
{"Name", "Gender", "Birth Date", "Educational Background", "Contact Number", "Position", "ID"},
{"Allen", "Male", "1990-02-10", "Bachelor", "24756854", "Mechanic", "0021"},
{"Patrick", "Male", "1985-06-08", "Master", "59863247", "Mechanic", "0022"},
{"Jenna", "Female", "1989-11-25", "Bachelor", "79540352", "Sales", "0023"},
{"Tommy", "Male", "1988-04-16", "Master", "52014060", "Mechanic", "0024"},
{"Christina", "Female", "1998-01-21", "Bachelor", "35401489", "HR", "0025"}
};
//Import data from DataTable to worksheet
sheet.insertArray(twoDimensionalArray,2,1);
//Set row height of a range
sheet.getRange().get("A2:G7").setRowHeight(15);
//Set column width
sheet.setColumnWidth(2,15);
sheet.setColumnWidth(3,21);
sheet.setColumnWidth(4,15);
//Set border style of a range
sheet.getRange().get("A2:G7").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").borderInside(LineStyleType.Thin);
sheet.getRange().get("A2:G2").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").getBorders().setKnownColor(ExcelColors.Black);
//Save to a .xlsx file
wb.saveToFile("output/NewSpreadsheet.xlsx", FileFormat.Version2016);
}
}

Чтение данных рабочего листа в Java
Метод CellRange.getValue() возвращает числовое значение или текстовое значение ячейки в виде строки. Чтобы получить данные всего листа или диапазона ячеек, пройдитесь по ячейкам внутри него. Ниже приведены шаги по получению данных листа с помощью Spire.XLS for Java.
- Создайте объект книги.
- Загрузите документ Excel с помощью метода Workbook.loadFromFile().
- Получите конкретный лист, используя метод Workbook.getWorksheets().get(index).
- Получите диапазон ячеек, содержащий данные, с помощью метода Worksheet.getAllocatedRange().
- Перебирайте строки и столбцы, чтобы получить ячейки в диапазоне, и возвращайте значение каждой ячейки с помощью метода CellRange.getValue().
- Java
import com.spire.xls.CellRange;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReadData {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Get the cell range containing data
CellRange locatedRange = sheet.getAllocatedRange();
//Iterate through the rows
for (int i = 0; i < locatedRange.getRows().length; i++) {
//Iterate through the columns
for (int j = 0; j < locatedRange.getColumnCount(); j++) {
//Get data of a specific cell
System.out.print(locatedRange.get(i + 1, j + 1).getValue() + " ");
}
System.out.println();
}
}
}

Обновление документа Excel в Java
Чтобы изменить значение определенной ячейки, просто присвойте ей значение с помощью метода Worksheet.getRange().setValue(). Ниже приведены подробные шаги.
- Создайте объект книги.
- Загрузите документ Excel с помощью метода Workbook.LoadFromFile().
- Получите конкретный лист через свойство Workbook.Worksheets[index].
- Измените значение определенной ячейки с помощью свойства Worksheet.Range.Value.
- Сохраните книгу в файл Excel, используя метод Workbook.SaveToFile().
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class UpdateExcel {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Change the value of a specific cell
sheet.getRange().get("A1").setValue("Updated Value");
//Save to file
wb.saveToFile("output/Updated.xlsx", ExcelVersion.Version2016);
}
}

Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
Java: Excel-Dokumente erstellen, lesen oder aktualisieren
Inhaltsverzeichnis
Mit Maven installieren
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>14.1.3</version>
</dependency>
verwandte Links
Die Excel-Tabelle ist ein beliebtes Dateiformat, mit dem Benutzer Daten in Tabellen anordnen, analysieren und anzeigen können. Die Fähigkeit zur programmgesteuerten Interaktion mit Excel-Dateien ist wertvoll für die Automatisierung und Integration ihrer Funktionen in Software. Dies ist insbesondere dann von Vorteil, wenn Sie mit umfangreichen Datensätzen, komplexen Berechnungen oder der dynamischen Generierung/Aktualisierung von Daten arbeiten. In diesem Artikel erfahren Sie, wie das geht Erstellen, lesen oder aktualisieren Sie Excel-Dokumente in Java mit Spire.XLS for Java.
- Erstellen Sie ein Excel-Dokument in Java
- Lesen Sie Daten eines Arbeitsblatts in Java
- Aktualisieren Sie ein Excel-Dokument in Java
Installieren Sie Spire.XLS for Java
Zunächst müssen Sie die Datei Spire.Xls.jar als Abhängigkeit zu Ihrem Java-Programm hinzufügen. Die JAR-Datei kann über diesen Linkheruntergeladen werden. Wenn Sie Maven verwenden, können Sie die JAR-Datei einfach in Ihre Anwendung importieren, indem Sie den folgenden Code zur pom.xml-Datei Ihres Projekts hinzufügen.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>16.2.6</version>
</dependency>
</dependencies>
Erstellen Sie ein Excel-Dokument in Java
Spire.XLS for Java bietet eine Vielzahl von Klassen und Schnittstellen, die Sie zum Erstellen und Bearbeiten von Excel-Dokumenten verwenden können. Hier ist eine Liste wichtiger Klassen, Eigenschaften und Methoden, die in diesem Artikel beteiligt sind.
| Mitglied | Beschreibung |
| Arbeitsbuchklasse | Stellt ein Excel-Arbeitsmappenmodell dar. |
| Workbook.getWorksheets().add()-Methode | Fügt der Arbeitsmappe ein Arbeitsblatt hinzu. |
| Workbook.saveToFile()-Methode | Speichert die Arbeitsmappe in einem Excel-Dokument. |
| Arbeitsblattklasse | Stellt ein Arbeitsblatt in einer Arbeitsmappe dar. |
| Worksheet.getRange()-Methode | Ruft eine bestimmte Zelle oder einen bestimmten Zellbereich aus dem Arbeitsblatt ab. |
| Worksheet.insertArray()-Methode | Importiert Daten aus einem Array in ein Arbeitsblatt. |
| CellRange-Klasse | Stellt eine Zelle oder einen Zellbereich im Arbeitsblatt dar. |
| CellRange.setValue()-Methode | Legt den Wert einer Zelle fest. |
| CellRange.getValue()-Methode | Ruft den Wert einer Zelle ab. |
Im Folgenden finden Sie die Schritte zum Erstellen eines Excel-Dokuments von Grund auf mit Spire.XLS for Java.
- Erstellen Sie ein Workbook-Objekt.
- Fügen Sie ein Arbeitsblatt mit der Methode Workbook.getWorksheets().add() hinzu.
- Schreiben Sie Daten mit der Methode Worksheet.getRange.setValue() in eine bestimmte Zelle.
- Importieren Sie Daten aus einem Array in das Arbeitsblatt mit der Methode .
- Speichern Sie die Arbeitsmappe mit der Methode Workbook.saveToFile() in einem Excel-Dokument.
- Java
import com.spire.xls.*;
public class CreateSpreadsheet {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Remove default worksheets
wb.getWorksheets().clear();
//Add a worksheet and name it "Employee"
Worksheet sheet = wb.getWorksheets().add("Employee");
//Merge the cells between A1 and G1
sheet.getRange().get("A1:G1").merge();
//Write data to A1 and apply formatting to it
sheet.getRange().get("A1").setValue("Basic Information of Employees of Huanyu Automobile Company");
sheet.getRange().get("A1").setHorizontalAlignment(HorizontalAlignType.Center);
sheet.getRange().get("A1").setVerticalAlignment(VerticalAlignType.Center);
sheet.getRange().get("A1").getStyle().getFont().isBold(true);
sheet.getRange().get("A1").getStyle().getFont().setSize(13);
//Set row height of the first row
sheet.setRowHeight(1,30);
//Create a two-dimensional array
String[][] twoDimensionalArray = new String[][]{
{"Name", "Gender", "Birth Date", "Educational Background", "Contact Number", "Position", "ID"},
{"Allen", "Male", "1990-02-10", "Bachelor", "24756854", "Mechanic", "0021"},
{"Patrick", "Male", "1985-06-08", "Master", "59863247", "Mechanic", "0022"},
{"Jenna", "Female", "1989-11-25", "Bachelor", "79540352", "Sales", "0023"},
{"Tommy", "Male", "1988-04-16", "Master", "52014060", "Mechanic", "0024"},
{"Christina", "Female", "1998-01-21", "Bachelor", "35401489", "HR", "0025"}
};
//Import data from DataTable to worksheet
sheet.insertArray(twoDimensionalArray,2,1);
//Set row height of a range
sheet.getRange().get("A2:G7").setRowHeight(15);
//Set column width
sheet.setColumnWidth(2,15);
sheet.setColumnWidth(3,21);
sheet.setColumnWidth(4,15);
//Set border style of a range
sheet.getRange().get("A2:G7").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").borderInside(LineStyleType.Thin);
sheet.getRange().get("A2:G2").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").getBorders().setKnownColor(ExcelColors.Black);
//Save to a .xlsx file
wb.saveToFile("output/NewSpreadsheet.xlsx", FileFormat.Version2016);
}
}

Lesen Sie Daten eines Arbeitsblatts in Java
Die Methode CellRange.getValue() gibt den Zahlenwert oder Textwert einer Zelle als Zeichenfolge zurück. Um Daten eines gesamten Arbeitsblatts oder eines Zellbereichs abzurufen, durchlaufen Sie die darin enthaltenen Zellen. Im Folgenden finden Sie die Schritte zum Abrufen von Daten eines Arbeitsblatts mit Spire.XLS for Java.
- Erstellen Sie ein Workbook-Objekt.
- Laden Sie ein Excel-Dokument mit der Methode Workbook.loadFromFile().
- Rufen Sie ein bestimmtes Arbeitsblatt mit der Methode Workbook.getWorksheets().get(index) ab.
- Rufen Sie den Zellbereich mit Daten mit der Methode Worksheet.getAllocatedRange() ab.
- Durchlaufen Sie die Zeilen und Spalten, um Zellen innerhalb des Bereichs zu erhalten, und geben Sie den Wert jeder Zelle mithilfe der Methode CellRange.getValue() zurück.
- Java
import com.spire.xls.CellRange;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReadData {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Get the cell range containing data
CellRange locatedRange = sheet.getAllocatedRange();
//Iterate through the rows
for (int i = 0; i < locatedRange.getRows().length; i++) {
//Iterate through the columns
for (int j = 0; j < locatedRange.getColumnCount(); j++) {
//Get data of a specific cell
System.out.print(locatedRange.get(i + 1, j + 1).getValue() + " ");
}
System.out.println();
}
}
}

Aktualisieren Sie ein Excel-Dokument in Java
Um den Wert einer bestimmten Zelle zu ändern, weisen Sie ihr einfach mit der Methode Worksheet.getRange().setValue() einen neuen Wert zu. Im Folgenden finden Sie die detaillierten Schritte.
- Erstellen Sie ein Workbook-Objekt.
- Laden Sie ein Excel-Dokument mit der Methode Workbook.LoadFromFile().
- Rufen Sie ein bestimmtes Arbeitsblatt über die Eigenschaft Workbook.Worksheets[index] ab.
- Ändern Sie den Wert einer bestimmten Zelle mithilfe der Worksheet.Range.Value-Eigenschaft.
- Speichern Sie die Arbeitsmappe mit der Methode Workbook.SaveToFile() in einer Excel-Datei.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class UpdateExcel {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Change the value of a specific cell
sheet.getRange().get("A1").setValue("Updated Value");
//Save to file
wb.saveToFile("output/Updated.xlsx", ExcelVersion.Version2016);
}
}

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.
Java: crear, leer o actualizar documentos de Excel
Tabla de contenido
Instalar con Maven
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>14.1.3</version>
</dependency>
enlaces relacionados
La hoja de cálculo de Excel es un formato de archivo popular que permite a los usuarios organizar, analizar y mostrar datos en tablas. La capacidad de interactuar mediante programación con archivos de Excel es valiosa para automatizar e integrar sus funciones en el software. Esto es especialmente beneficioso cuando se trata de conjuntos de datos extensos, cálculos complejos o generación/actualización dinámica de datos. En este artículo, aprenderá cómo cree, lea o actualice un documento de Excel en Java utilizando Spire.XLS for Java.
- Crear un documento de Excel en Java
- Leer datos de una hoja de trabajo en Java
- Actualizar un documento de Excel en Java
Instalar Spire.XLS for Java
Primero, debe agregar el archivo Spire.Xls.jar como una dependencia en su programa Java. El archivo JAR se puede descargar desde este enlace. Si usa Maven, puede importar fácilmente el archivo JAR en su aplicación agregando el siguiente código al archivo pom.xml de su proyecto.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>16.2.6</version>
</dependency>
</dependencies>
Crear un documento de Excel en Java
Spire.XLS for Java ofrece una variedad de clases e interfaces que puede utilizar para crear y editar documentos de Excel. Aquí hay una lista de clases, propiedades y métodos importantes involucrados en este artículo.
| Miembro | Descripción |
| clase de libro de trabajo | Representa un modelo de libro de Excel. |
| Método Workbook.getWorksheets().add() | Agrega una hoja de trabajo al libro de trabajo. |
| Método Workbook.saveToFile() | Guarda el libro en un documento de Excel. |
| clase de hoja de trabajo | Representa una hoja de trabajo en un libro de trabajo. |
| Método Worksheet.getRange() | Obtiene una celda o rango de celdas específico de la hoja de trabajo. |
| Método Worksheet.insertArray() | Importa datos de una matriz a una hoja de trabajo. |
| clase rango de celdas | Representa una celda o rango de celdas en la hoja de trabajo. |
| Método CellRange.setValue() | Establece el valor de una celda. |
| Método CellRange.getValue() | Obtiene el valor de una celda. |
Los siguientes son los pasos para crear un documento de Excel desde cero usando Spire.XLS for Java.
- Cree un objeto de libro de trabajo.
- Agregue una hoja de trabajo usando el método Workbook.getWorksheets().add().
- Escriba datos en una celda específica utilizando el método Worksheet.getRange.setValue().
- Importe datos de una matriz a la hoja de trabajo utilizando el método Worksheet.insertArray().
- Guarde el libro de trabajo en un documento de Excel utilizando el método Workbook.saveToFile().
- Java
import com.spire.xls.*;
public class CreateSpreadsheet {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Remove default worksheets
wb.getWorksheets().clear();
//Add a worksheet and name it "Employee"
Worksheet sheet = wb.getWorksheets().add("Employee");
//Merge the cells between A1 and G1
sheet.getRange().get("A1:G1").merge();
//Write data to A1 and apply formatting to it
sheet.getRange().get("A1").setValue("Basic Information of Employees of Huanyu Automobile Company");
sheet.getRange().get("A1").setHorizontalAlignment(HorizontalAlignType.Center);
sheet.getRange().get("A1").setVerticalAlignment(VerticalAlignType.Center);
sheet.getRange().get("A1").getStyle().getFont().isBold(true);
sheet.getRange().get("A1").getStyle().getFont().setSize(13);
//Set row height of the first row
sheet.setRowHeight(1,30);
//Create a two-dimensional array
String[][] twoDimensionalArray = new String[][]{
{"Name", "Gender", "Birth Date", "Educational Background", "Contact Number", "Position", "ID"},
{"Allen", "Male", "1990-02-10", "Bachelor", "24756854", "Mechanic", "0021"},
{"Patrick", "Male", "1985-06-08", "Master", "59863247", "Mechanic", "0022"},
{"Jenna", "Female", "1989-11-25", "Bachelor", "79540352", "Sales", "0023"},
{"Tommy", "Male", "1988-04-16", "Master", "52014060", "Mechanic", "0024"},
{"Christina", "Female", "1998-01-21", "Bachelor", "35401489", "HR", "0025"}
};
//Import data from DataTable to worksheet
sheet.insertArray(twoDimensionalArray,2,1);
//Set row height of a range
sheet.getRange().get("A2:G7").setRowHeight(15);
//Set column width
sheet.setColumnWidth(2,15);
sheet.setColumnWidth(3,21);
sheet.setColumnWidth(4,15);
//Set border style of a range
sheet.getRange().get("A2:G7").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").borderInside(LineStyleType.Thin);
sheet.getRange().get("A2:G2").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").getBorders().setKnownColor(ExcelColors.Black);
//Save to a .xlsx file
wb.saveToFile("output/NewSpreadsheet.xlsx", FileFormat.Version2016);
}
}

Leer datos de una hoja de trabajo en Java
El método CellRange.getValue() devuelve el valor numérico o el valor de texto de una celda como una cadena. Para obtener datos de una hoja de trabajo completa o un rango de celdas, recorra las celdas que contiene. Los siguientes son los pasos para obtener datos de una hoja de trabajo usando Spire.XLS for Java.
- Cree un objeto de libro de trabajo.
- Cargue un documento de Excel utilizando el método Workbook.loadFromFile().
- Obtenga una hoja de trabajo específica utilizando el método Workbook.getWorksheets().get(index).
- Obtenga el rango de celdas que contiene datos utilizando el método Worksheet.getAllocatedRange().
- Itere a través de las filas y columnas para obtener celdas dentro del rango y devuelva el valor de cada celda usando el método CellRange.getValue().
- Java
import com.spire.xls.CellRange;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReadData {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Get the cell range containing data
CellRange locatedRange = sheet.getAllocatedRange();
//Iterate through the rows
for (int i = 0; i < locatedRange.getRows().length; i++) {
//Iterate through the columns
for (int j = 0; j < locatedRange.getColumnCount(); j++) {
//Get data of a specific cell
System.out.print(locatedRange.get(i + 1, j + 1).getValue() + " ");
}
System.out.println();
}
}
}

Actualizar un documento de Excel en Java
Para cambiar el valor de una determinada celda, simplemente vuelva a asignarle un valor utilizando el método Worksheet.getRange().setValue(). Los siguientes son los pasos detallados.
- Cree un objeto de libro de trabajo.
- Cargue un documento de Excel utilizando el método Workbook.LoadFromFile().
- Obtenga una hoja de trabajo específica a través de la propiedad Workbook.Worksheets[index].
- Cambie el valor de una celda en particular a través de la propiedad Worksheet.Range.Value.
- Guarde el libro en un archivo de Excel utilizando el método Workbook.SaveToFile().
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class UpdateExcel {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Change the value of a specific cell
sheet.getRange().get("A1").setValue("Updated Value");
//Save to file
wb.saveToFile("output/Updated.xlsx", ExcelVersion.Version2016);
}
}

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.
Java: Excel 문서 생성, 읽기 또는 업데이트
메이븐으로 설치
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>14.1.3</version></dependency>
관련된 링크들
Excel 스프레드시트는 사용자가 테이블의 데이터를 정렬, 분석 및 표시할 수 있는 널리 사용되는 파일 형식입니다. Excel 파일과 프로그래밍 방식으로 상호 작용하는 기능은 해당 기능을 소프트웨어에 자동화하고 통합하는 데 유용합니다. 이는 광범위한 데이터 세트, 복잡한 계산을 처리하거나 데이터를 동적으로 생성/업데이트할 때 특히 유용합니다. 이 기사에서는 다음 방법을 배웁니다 Java로 Excel 문서 생성, 읽기 또는 업데이트 Spire.XLS for Java사용합니다.
Spire.XLS for Java 설치
먼저 Spire.Xls.jar 파일을 Java 프로그램의 종속성으로 추가해야 합니다. JAR 파일은 이 링크에서 다운로드할 수 있습니다. Maven을 사용하는 경우 프로젝트의 pom.xml 파일에 다음 코드를 추가하여 애플리케이션에서 JAR 파일을 쉽게 가져올 수 있습니다.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>16.2.6</version>
</dependency>
</dependencies>
Java로 Excel 문서 만들기
Spire.XLS for Java는 Excel 문서를 생성하고 편집하는 데 사용할 수 있는 다양한 클래스와 인터페이스를 제공합니다. 다음은 이 기사와 관련된 중요한 클래스, 속성 및 메서드 목록입니다.
| 회원 | 설명 |
| 워크북 수업 | Excel 통합 문서 모델을 나타냅니다. |
| Workbook.getWorksheets().add() 메서드 | 통합 문서에 워크시트를 추가합니다. |
| Workbook.saveToFile() 메서드 | 통합 문서를 Excel 문서에 저장합니다. |
| 워크시트 수업 | 통합 문서의 워크시트를 나타냅니다. |
| Worksheet.getRange() 메서드 | 워크시트에서 특정 셀이나 셀 범위를 가져옵니다. |
| Worksheet.insertArray() 메서드 | 배열의 데이터를 워크시트로 가져옵니다. |
| CellRange 클래스 | 워크시트의 셀 또는 셀 범위를 나타냅니다. |
| CellRange.setValue() 메서드 | 셀의 값을 설정합니다. |
| CellRange.getValue() 메서드 | 셀의 값을 가져옵니다. |
다음은 Spire.XLS for Java 사용하여 처음부터 Excel 문서를 만드는 단계입니다.
- 통합 문서 개체를 만듭니다.
- Workbook.getWorksheets().add() 메서드를 사용하여 워크시트를 추가합니다.
- Worksheet.getRange.setValue() 메서드를 사용하여 특정 셀에 데이터를 씁니다.
- Worksheet.insertArray() 메서드를 사용하여 배열의 데이터를 워크시트로 가져옵니다.
- Workbook.saveToFile() 메서드를 사용하여 통합 문서를 Excel 문서에 저장합니다.
- Java
import com.spire.xls.*;
public class CreateSpreadsheet {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Remove default worksheets
wb.getWorksheets().clear();
//Add a worksheet and name it "Employee"
Worksheet sheet = wb.getWorksheets().add("Employee");
//Merge the cells between A1 and G1
sheet.getRange().get("A1:G1").merge();
//Write data to A1 and apply formatting to it
sheet.getRange().get("A1").setValue("Basic Information of Employees of Huanyu Automobile Company");
sheet.getRange().get("A1").setHorizontalAlignment(HorizontalAlignType.Center);
sheet.getRange().get("A1").setVerticalAlignment(VerticalAlignType.Center);
sheet.getRange().get("A1").getStyle().getFont().isBold(true);
sheet.getRange().get("A1").getStyle().getFont().setSize(13);
//Set row height of the first row
sheet.setRowHeight(1,30);
//Create a two-dimensional array
String[][] twoDimensionalArray = new String[][]{
{"Name", "Gender", "Birth Date", "Educational Background", "Contact Number", "Position", "ID"},
{"Allen", "Male", "1990-02-10", "Bachelor", "24756854", "Mechanic", "0021"},
{"Patrick", "Male", "1985-06-08", "Master", "59863247", "Mechanic", "0022"},
{"Jenna", "Female", "1989-11-25", "Bachelor", "79540352", "Sales", "0023"},
{"Tommy", "Male", "1988-04-16", "Master", "52014060", "Mechanic", "0024"},
{"Christina", "Female", "1998-01-21", "Bachelor", "35401489", "HR", "0025"}
};
//Import data from DataTable to worksheet
sheet.insertArray(twoDimensionalArray,2,1);
//Set row height of a range
sheet.getRange().get("A2:G7").setRowHeight(15);
//Set column width
sheet.setColumnWidth(2,15);
sheet.setColumnWidth(3,21);
sheet.setColumnWidth(4,15);
//Set border style of a range
sheet.getRange().get("A2:G7").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").borderInside(LineStyleType.Thin);
sheet.getRange().get("A2:G2").borderAround(LineStyleType.Medium);
sheet.getRange().get("A2:G7").getBorders().setKnownColor(ExcelColors.Black);
//Save to a .xlsx file
wb.saveToFile("output/NewSpreadsheet.xlsx", FileFormat.Version2016);
}
}

Java에서 워크시트 데이터 읽기
CellRange.getValue() 메서드는 셀의 숫자 값이나 텍스트 값을 문자열로 반환합니다. 전체 워크시트나 셀 범위의 데이터를 얻으려면 그 안의 셀을 반복하세요. 다음은 Spire.XLS for Java를 사용하여 워크시트의 데이터를 가져오는 단계입니다.
- 통합 문서 개체를 만듭니다.
- Workbook.loadFromFile() 메서드를 사용하여 Excel 문서를 로드합니다.
- Workbook.getWorksheets().get(index) 메서드를 사용하여 특정 워크시트를 가져옵니다.
- Worksheet.getAllocationRange() 메서드를 사용하여 데이터가 포함된 셀 범위를 가져옵니다.
- 행과 열을 반복하여 범위 내의 셀을 가져오고 CellRange.getValue() 메서드를 사용하여 각 셀의 값을 반환합니다.
- Java
import com.spire.xls.CellRange;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ReadData {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Get the cell range containing data
CellRange locatedRange = sheet.getAllocatedRange();
//Iterate through the rows
for (int i = 0; i < locatedRange.getRows().length; i++) {
//Iterate through the columns
for (int j = 0; j < locatedRange.getColumnCount(); j++) {
//Get data of a specific cell
System.out.print(locatedRange.get(i + 1, j + 1).getValue() + " ");
}
System.out.println();
}
}
}

Java에서 Excel 문서 업데이트
특정 셀의 값을 변경하려면 Worksheet.getRange().setValue() 메서드를 사용하여 해당 셀에 값을 다시 할당하면 됩니다. 자세한 단계는 다음과 같습니다.
- 통합 문서 개체를 만듭니다.
- Workbook.LoadFromFile() 메서드를 사용하여 Excel 문서를 로드합니다.
- Workbook.Worksheets[index] 속성을 통해 특정 워크시트를 가져옵니다.
- Worksheet.Range.Value 속성을 통해 특정 셀의 값을 변경합니다.
- Workbook.SaveToFile() 메서드를 사용하여 통합 문서를 Excel 파일에 저장합니다.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class UpdateExcel {
public static void main(String[] args) {
//Create a Workbook object
Workbook wb = new Workbook();
//Load an existing Excel file
wb.loadFromFile("C:/Users/Administrator/Desktop/NewSpreadsheet.xlsx");
//Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
//Change the value of a specific cell
sheet.getRange().get("A1").setValue("Updated Value");
//Save to file
wb.saveToFile("output/Updated.xlsx", ExcelVersion.Version2016);
}
}

임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.