Java: Konvertieren Sie Excel in Office Open XML und umgekehrt
Inhaltsverzeichnis
Mit Maven installieren
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
verwandte Links
Office Open XML (auch als OOXML bezeichnet) ist ein komprimiertes, XML-basiertes Format für Excel-, Word- und Präsentationsdokumente. Manchmal müssen Sie möglicherweise eine Excel-Datei in Office Open XML konvertieren, um sie für verschiedene Anwendungen und Plattformen lesbar zu machen. Ebenso möchten Sie möglicherweise Office Open XML für Datenberechnungen in Excel konvertieren. In diesem Artikel erfahren Sie, wie Sie Excel in Java in Office Open XML und umgekehrt konvertieren Verwendung der Spire.XLS for Java-Bibliothek.
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 Link heruntergeladen 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>14.11.0</version> </dependency> </dependencies>
Konvertieren Sie Excel in Office Open XML in Java
Im Folgenden finden Sie die Schritte zum Konvertieren einer Excel-Datei in Office Open XML:
- Erstellen Sie eine Instanz der Workbook-Klasse.
- Laden Sie eine Excel-Datei mit der Methode Workbook.loadFromFile().
- Rufen Sie die Methode Workbook.saveAsXml() auf, um die Excel-Datei als Office Open XML zu speichern.
- Java
import com.spire.xls.Workbook; public class ExcelToOpenXML { public static void main(String []args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.loadFromFile("Sample.xlsx"); //Save as Office Open XML file format workbook.saveAsXml("ToXML.xml"); } }
Konvertieren Sie Office Open XML in Java in Excel
Im Folgenden finden Sie die Schritte zum Konvertieren einer Office Open XML-Datei in Excel:
- Erstellen Sie eine Instanz der Workbook-Klasse.
- Laden Sie eine Office Open XML-Datei mit der Datei Workbook.loadFromXml().
- Rufen Sie die Methode Workbook.saveToFile() auf, um die Office Open XML-Datei als Excel zu speichern.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; public class OpenXmlToExcel { public static void main(String []args){ //Create an instance of Workbook class Workbook workbook = new Workbook(); //Load an Office Open XML file workbook.loadFromXml("ToXML.xml"); //Save as Excel XLSX file format workbook.saveToFile("ToExcel.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: convierta Excel a Office Open XML y viceversa
Tabla de contenido
Instalar con Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
enlaces relacionados
Office Open XML (también conocido como OOXML) es un formato comprimido basado en XML para documentos de Excel, Word y presentaciones. A veces, es posible que necesites convertir un archivo de Excel a Office Open XML para que sea legible en varias aplicaciones y plataformas. Del mismo modo, es posible que también desee convertir Office Open XML a Excel para realizar cálculos de datos. En este artículo, aprenderá cómo convertir Excel a Office Open XML y viceversa en Java utilizando la biblioteca Spire.XLS for Java.
Instalar Spire.XLS for Java
En primer lugar, 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>14.11.0</version> </dependency> </dependencies>
Convierta Excel a Office Open XML en Java
Los siguientes son los pasos para convertir un archivo de Excel a Office Open XML:
- Cree una instancia de la clase Libro de trabajo.
- Cargue un archivo de Excel utilizando el método Workbook.loadFromFile().
- Llame al método Workbook.saveAsXml() para guardar el archivo de Excel como Office Open XML.
- Java
import com.spire.xls.Workbook; public class ExcelToOpenXML { public static void main(String []args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.loadFromFile("Sample.xlsx"); //Save as Office Open XML file format workbook.saveAsXml("ToXML.xml"); } }
Convierta Office Open XML a Excel en Java
Los siguientes son los pasos para convertir un archivo Office Open XML a Excel:
- Cree una instancia de la clase Libro de trabajo.
- Cargue un archivo Office Open XML utilizando el archivo Workbook.loadFromXml().
- Llame al método Workbook.saveToFile() para guardar el archivo Office Open XML como Excel.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; public class OpenXmlToExcel { public static void main(String []args){ //Create an instance of Workbook class Workbook workbook = new Workbook(); //Load an Office Open XML file workbook.loadFromXml("ToXML.xml"); //Save as Excel XLSX file format workbook.saveToFile("ToExcel.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을 Office Open XML로 변환하고 그 반대로 변환
메이븐으로 설치
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
관련된 링크들
Office Open XML(OOXML이라고도 함)은 Excel, Word 및 프레젠테이션 문서를 위한 압축된 XML 기반 형식입니다. 때로는 다양한 응용 프로그램과 플랫폼에서 읽을 수 있도록 Excel 파일을 Office Open XML로 변환해야 할 수도 있습니다. 마찬가지로 데이터 계산을 위해 Office Open XML을 Excel로 변환할 수도 있습니다. 이 기사에서는 다음 방법을 배웁니다 Java에서 Excel을 Office Open XML로 변환하거나 그 반대로 변환 사용하여 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>14.11.0</version> </dependency> </dependencies>
Excel을 Java의 Office Open XML로 변환
다음은 Excel 파일을 Office Open XML로 변환하는 단계입니다.
- Workbook 클래스의 인스턴스를 만듭니다.
- Workbook.loadFromFile() 메서드를 사용하여 Excel 파일을 로드합니다.
- Workbook.saveAsXml() 메서드를 호출하여 Excel 파일을 Office Open XML로 저장합니다.
- Java
import com.spire.xls.Workbook; public class ExcelToOpenXML { public static void main(String []args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.loadFromFile("Sample.xlsx"); //Save as Office Open XML file format workbook.saveAsXml("ToXML.xml"); } }
Office Open XML을 Java의 Excel로 변환
다음은 Office Open XML 파일을 Excel로 변환하는 단계입니다.
- Workbook 클래스의 인스턴스를 만듭니다.
- Workbook.loadFromXml() 파일을 사용하여 Office Open XML 파일을 로드합니다.
- Workbook.saveToFile() 메서드를 호출하여 Office Open XML 파일을 Excel로 저장합니다.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; public class OpenXmlToExcel { public static void main(String []args){ //Create an instance of Workbook class Workbook workbook = new Workbook(); //Load an Office Open XML file workbook.loadFromXml("ToXML.xml"); //Save as Excel XLSX file format workbook.saveToFile("ToExcel.xlsx", ExcelVersion.Version2016); } }
임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
Java: converti Excel in Office Open XML e viceversa
Sommario
Installa con Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
Link correlati
Office Open XML (noto anche come OOXML) è un formato compresso basato su XML per documenti Excel, Word e presentazioni. A volte potrebbe essere necessario convertire un file Excel in Office Open XML per renderlo leggibile su varie applicazioni e piattaforme. Allo stesso modo, potresti anche voler convertire Office Open XML in Excel per i calcoli dei dati. In questo articolo imparerai come convertire Excel in Office Open XML e viceversa in Java utilizzando la libreria Spire.XLS for Java.
Installa Spire.XLS for Java
Prima di tutto, devi aggiungere il file Spire.Xls.jar come dipendenza nel tuo programma Java. Il file JAR può essere scaricato da questo collegamento. Se utilizzi Maven, puoi importare facilmente il file JAR nella tua applicazione aggiungendo il seguente codice al file pom.xml del tuo progetto.
<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>14.11.0</version> </dependency> </dependencies>
Converti Excel in Office Open XML in Java
Di seguito sono riportati i passaggi per convertire un file Excel in Office Open XML:
- Crea un'istanza della classe Workbook.
- Carica un file Excel utilizzando il metodo Workbook.loadFromFile().
- Chiama il metodo Workbook.saveAsXml() per salvare il file Excel come Office Open XML.
- Java
import com.spire.xls.Workbook; public class ExcelToOpenXML { public static void main(String []args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.loadFromFile("Sample.xlsx"); //Save as Office Open XML file format workbook.saveAsXml("ToXML.xml"); } }
Converti Office Open XML in Excel in Java
Di seguito sono riportati i passaggi per convertire un file Office Open XML in Excel:
- Crea un'istanza della classe Workbook.
- Caricare un file Office Open XML utilizzando il file Workbook.loadFromXml().
- Chiama il metodo Workbook.saveToFile() per salvare il file Office Open XML come Excel.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; public class OpenXmlToExcel { public static void main(String []args){ //Create an instance of Workbook class Workbook workbook = new Workbook(); //Load an Office Open XML file workbook.loadFromXml("ToXML.xml"); //Save as Excel XLSX file format workbook.saveToFile("ToExcel.xlsx", ExcelVersion.Version2016); } }
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.
Java : convertir Excel en Office Open XML et vice versa
Table des matières
Installer avec Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
Liens connexes
Office Open XML (également appelé OOXML) est un format XML compressé pour les documents Excel, Word et Présentation. Parfois, vous devrez peut-être convertir un fichier Excel en Office Open XML afin de le rendre lisible sur diverses applications et plates-formes. De même, vous souhaiterez peut-être également convertir Office Open XML en Excel pour les calculs de données. Dans cet article, vous apprendrez comment convertir Excel en Office Open XML et vice versa en Java à l'aide de la bibliothèque Spire.XLS for Java library.
Installer Spire.XLS for Java
Tout d'abord, vous devez ajouter le fichier Spire.Xls.jar en tant que dépendance dans votre programme Java. Le fichier JAR peut être téléchargé à partir de ce lien. Si vous utilisez Maven, vous pouvez facilement importer le fichier JAR dans votre application en ajoutant le code suivant au fichier pom.xml de votre projet.
<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>14.11.0</version> </dependency> </dependencies>
Convertir Excel en Office Open XML en Java
Voici les étapes pour convertir un fichier Excel en Office Open XML :
- Créez une instance de la classe Workbook.
- Chargez un fichier Excel à l'aide de la méthode Workbook.loadFromFile().
- Appelez la méthode Workbook.saveAsXml() pour enregistrer le fichier Excel au format Office Open XML.
- Java
import com.spire.xls.Workbook; public class ExcelToOpenXML { public static void main(String []args){ //Create a Workbook instance Workbook workbook = new Workbook(); //Load an Excel file workbook.loadFromFile("Sample.xlsx"); //Save as Office Open XML file format workbook.saveAsXml("ToXML.xml"); } }
Convertir Office Open XML en Excel en Java
Voici les étapes pour convertir un fichier Office Open XML en Excel :
- Créez une instance de la classe Workbook.
- Chargez un fichier Office Open XML à l'aide du fichier Workbook.loadFromXml().
- Appelez la méthode Workbook.saveToFile() pour enregistrer le fichier Office Open XML au format Excel.
- Java
import com.spire.xls.ExcelVersion; import com.spire.xls.Workbook; public class OpenXmlToExcel { public static void main(String []args){ //Create an instance of Workbook class Workbook workbook = new Workbook(); //Load an Office Open XML file workbook.loadFromXml("ToXML.xml"); //Save as Excel XLSX file format workbook.saveToFile("ToExcel.xlsx", ExcelVersion.Version2016); } }
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: Convert Excel to PDF
Table of Contents
Install with Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
Related Links
Using PDF as a format for sending documents ensures that no formatting changes will occur to the original document. Exporting Excel to PDF is a common practice in many cases. This article introduces how to convert a whole Excel document or a specific worksheet to PDF using Spire.XLS for Java.
Install Spire.XLS for Java
First of all, 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>14.11.0</version> </dependency> </dependencies>
Convert a Whole Excel File to PDF
The following are the steps to convert a whole Excel document to PDF.
- Create a Workbook object.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Set the Excel to PDF conversion options through the methods under the ConverterSetting object, which is returned by Workbook.getConverterSetting() method.
- Convert the whole Excel document to PDF using Workbook.saveToFile() method.
- Java
import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ConvertExcelToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to page when converting workbook.getConverterSetting().setSheetFitToPage(true); //Save the resulting document to a specified path workbook.saveToFile("output/ExcelToPdf.pdf", FileFormat.PDF); } }
Convert a Specific Worksheet to PDF
The following are the steps to convert a specific worksheet to PDF.
- Create a Workbook object.
- Load a sample Excel document using Workbook.loadFromFile() method.
- Set the Excel to PDF conversion options through the methods under the ConverterSetting object, which is returned by Workbook.getConverterSetting() method.
- Get a specific worksheet using Workbook.getWorksheets().get() method.
- Convert the worksheet to PDF using Worksheet.saveToPdf() method.
- Java
import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ConvertWorksheetToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to width when converting workbook.getConverterSetting().setSheetFitToWidth(true); //Get the first worksheet Worksheet worksheet = workbook.getWorksheets().get(0); //Convert to PDF and save the resulting document to a specified path worksheet.saveToPdf("output/WorksheetToPdf.pdf"); } }
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: Converter Excel em PDF
Índice
Instalar com Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
Links Relacionados
Usar PDF como formato para envio de documentos garante que nenhuma alteração de formatação ocorrerá no documento original. Exportar Excel para PDF é uma prática comum em muitos casos. Este artigo apresenta como converta um documento Excel inteiro ou uma planilha específica em PDF usando Spire.XLS for Java.
Instale Spire.XLS for Java
Primeiro de tudo, você deve 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>14.11.0</version> </dependency> </dependencies>
Converta um arquivo Excel inteiro em PDF
A seguir estão as etapas para converter um documento Excel inteiro em PDF.
- Crie um objeto Pasta de trabalho.
- Carregue um documento Excel de amostra usando o método Workbook.loadFromFile().
- Defina as opções de conversão de Excel para PDF por meio dos métodos no objeto ConverterSetting, que é retornado pelo método Workbook.getConverterSetting().
- Converta todo o documento Excel em PDF usando o método Workbook.saveToFile().
- Java
import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ConvertExcelToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to page when converting workbook.getConverterSetting().setSheetFitToPage(true); //Save the resulting document to a specified path workbook.saveToFile("output/ExcelToPdf.pdf", FileFormat.PDF); } }
Converter uma planilha específica em PDF
A seguir estão as etapas para converter uma planilha específica em PDF.
- Crie um objeto Pasta de trabalho.
- Carregue um documento Excel de amostra usando o método Workbook.loadFromFile().
- Defina as opções de conversão de Excel para PDF por meio dos métodos no objeto ConverterSetting, que é retornado pelo método Workbook.getConverterSetting().
- Obtenha uma planilha específica usando o método Workbook.getWorksheets().get().
- Converta a planilha em PDF usando o método Worksheet.saveToPdf().
- Java
import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ConvertWorksheetToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to width when converting workbook.getConverterSetting().setSheetFitToWidth(true); //Get the first worksheet Worksheet worksheet = workbook.getWorksheets().get(0); //Convert to PDF and save the resulting document to a specified path worksheet.saveToPdf("output/WorksheetToPdf.pdf"); } }
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 в PDF
Оглавление
Установить с помощью Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
Ссылки по теме
Использование PDF в качестве формата для отправки документов гарантирует, что в исходном документе не произойдет никаких изменений форматирования. Экспорт Excel в PDF во многих случаях является обычной практикой. В этой статье рассказывается, как конвертируйте весь документ Excel или конкретный лист в PDF с помощью Spire.XLS for 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>14.11.0</version> </dependency> </dependencies>
Конвертировать весь файл Excel в PDF
Ниже приведены шаги по преобразованию всего документа Excel в PDF.
- Создайте объект книги.
- Загрузите образец документа Excel с помощью метода Workbook.loadFromFile().
- Установите параметры преобразования Excel в PDF с помощью методов объекта ConverterSetting, который возвращается методом Workbook.getConverterSetting().
- Преобразуйте весь документ Excel в PDF с помощью метода Workbook.saveToFile().
- Java
import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ConvertExcelToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to page when converting workbook.getConverterSetting().setSheetFitToPage(true); //Save the resulting document to a specified path workbook.saveToFile("output/ExcelToPdf.pdf", FileFormat.PDF); } }
Преобразование определенного листа в PDF
Ниже приведены шаги по преобразованию определенного листа в PDF.
- Создайте объект книги.
- Загрузите образец документа Excel с помощью метода Workbook.loadFromFile().
- Установите параметры преобразования Excel в PDF с помощью методов объекта ConverterSetting, который возвращается методом Workbook.getConverterSetting().
- Получите конкретный лист, используя метод Workbook.getWorksheets().get().
- Преобразуйте рабочий лист в PDF с помощью метода Worksheet.saveToPdf().
- Java
import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ConvertWorksheetToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to width when converting workbook.getConverterSetting().setSheetFitToWidth(true); //Get the first worksheet Worksheet worksheet = workbook.getWorksheets().get(0); //Convert to PDF and save the resulting document to a specified path worksheet.saveToPdf("output/WorksheetToPdf.pdf"); } }
Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
Java: Excel in PDF konvertieren
Inhaltsverzeichnis
Mit Maven installieren
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
verwandte Links
Durch die Verwendung von PDF als Format zum Versenden von Dokumenten wird sichergestellt, dass keine Formatierungsänderungen am Originaldokument vorgenommen werden. Der Export von Excel nach PDF ist in vielen Fällen eine gängige Praxis. In diesem Artikel erfahren Sie, wie das geht Konvertieren Sie ein ganzes Excel-Dokument oder ein bestimmtes Arbeitsblatt mit Spire.XLS for Javain PDF.
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 Link. heruntergeladen 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>14.11.0</version> </dependency> </dependencies>
Konvertieren Sie eine ganze Excel-Datei in PDF
Im Folgenden finden Sie die Schritte zum Konvertieren eines gesamten Excel-Dokuments in PDF.
- Erstellen Sie ein Workbook-Objekt.
- Laden Sie ein Beispiel-Excel-Dokument mit der Methode Workbook.loadFromFile().
- Legen Sie die Konvertierungsoptionen von Excel in PDF über die Methoden unter dem ConverterSetting-Objekt fest, das von der Workbook.getConverterSetting()-Methode zurückgegeben wird.
- Konvertieren Sie das gesamte Excel-Dokument mit der Methode Workbook.saveToFile() in PDF.
- Java
import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ConvertExcelToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to page when converting workbook.getConverterSetting().setSheetFitToPage(true); //Save the resulting document to a specified path workbook.saveToFile("output/ExcelToPdf.pdf", FileFormat.PDF); } }
Konvertieren Sie ein bestimmtes Arbeitsblatt in PDF
Im Folgenden finden Sie die Schritte zum Konvertieren eines bestimmten Arbeitsblatts in PDF.
- Erstellen Sie ein Workbook-Objekt.
- Laden Sie ein Beispiel-Excel-Dokument mit der Methode Workbook.loadFromFile().
- Legen Sie die Konvertierungsoptionen von Excel in PDF über die Methoden unter dem ConverterSetting-Objekt fest, das von der Workbook.getConverterSetting()-Methode zurückgegeben wird.
- Rufen Sie ein bestimmtes Arbeitsblatt mit der Methode Workbook.getWorksheets().get() ab.
- Konvertieren Sie das Arbeitsblatt mit der Methode Worksheet.saveToPdf() in PDF.
- Java
import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ConvertWorksheetToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to width when converting workbook.getConverterSetting().setSheetFitToWidth(true); //Get the first worksheet Worksheet worksheet = workbook.getWorksheets().get(0); //Convert to PDF and save the resulting document to a specified path worksheet.saveToPdf("output/WorksheetToPdf.pdf"); } }
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: convertir Excel a PDF
Tabla de contenido
Instalar con Maven
<dependency> <groupId>e-iceblue</groupId> <artifactId>spire.xls</artifactId> <version>14.1.3</version> </dependency>
enlaces relacionados
El uso de PDF como formato para enviar documentos garantiza que no se producirán cambios de formato en el documento original. Exportar Excel a PDF es una práctica común en muchos casos. Este artículo presenta cómo convierta un documento completo de Excel o una hoja de trabajo específica a PDF usando Spire.XLS for Java.
Instalar Spire.XLS for Java
En primer lugar, 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>14.11.0</version> </dependency> </dependencies>
Convertir un archivo completo de Excel a PDF
Los siguientes son los pasos para convertir un documento completo de Excel a PDF.
- Cree un objeto de libro de trabajo.
- Cargue un documento de Excel de muestra utilizando el método Workbook.loadFromFile().
- Configure las opciones de conversión de Excel a PDF a través de los métodos del objeto ConverterSetting, que devuelve el método Workbook.getConverterSetting().
- Convierta todo el documento de Excel a PDF utilizando el método Workbook.saveToFile().
- Java
import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ConvertExcelToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to page when converting workbook.getConverterSetting().setSheetFitToPage(true); //Save the resulting document to a specified path workbook.saveToFile("output/ExcelToPdf.pdf", FileFormat.PDF); } }
Convertir una hoja de trabajo específica a PDF
Los siguientes son los pasos para convertir una hoja de trabajo específica a PDF.
- Cree un objeto de libro de trabajo.
- Cargue un documento de Excel de muestra utilizando el método Workbook.loadFromFile().
- Configure las opciones de conversión de Excel a PDF a través de los métodos del objeto ConverterSetting, que devuelve el método Workbook.getConverterSetting().
- Obtenga una hoja de trabajo específica utilizando el método Workbook.getWorksheets().get().
- Convierta la hoja de trabajo a PDF usando el método Worksheet.saveToPdf().
- Java
import com.spire.xls.Workbook; import com.spire.xls.Worksheet; public class ConvertWorksheetToPdf { public static void main(String[] args) { //Create a Workbook instance and load an Excel file Workbook workbook = new Workbook(); workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx"); //Set worksheets to fit to width when converting workbook.getConverterSetting().setSheetFitToWidth(true); //Get the first worksheet Worksheet worksheet = workbook.getWorksheets().get(0); //Convert to PDF and save the resulting document to a specified path worksheet.saveToPdf("output/WorksheetToPdf.pdf"); } }
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.