Python Guide to Convert Markdown to HTML

Markdown (.md) is widely used in web development, documentation, and technical writing. Its simple syntax makes content easy to write and read. However, web browsers do not render Markdown directly. Converting Markdown to HTML ensures your content is structured, readable, and compatible with web platforms.

In this step-by-step guide, you will learn how to efficiently convert Markdown (.md) files into HTML using Python and Spire.Doc for Python, complete with practical code examples, clear instructions, and best practices for both single-file and batch conversions.

Table of Contents

What is Markdown?

Markdown is a lightweight markup language designed for readability and ease of writing. Unlike HTML, which can be verbose and harder to write by hand, Markdown uses simple syntax to indicate headings, lists, links, images, and more.

Example Markdown:

# This is a Heading

This is a paragraph with \*\*bold text\*\* and \*italic text\*.

- Item 1

- Item 2

Even in its raw form, Markdown is easy to read, which makes it popular for documentation, blogging, README files, and technical writing.

For more on Markdown syntax, see the Markdown Guide.

Why Convert Markdown to HTML?

While Markdown is excellent for authoring content, web browsers cannot render it natively. Converting Markdown to HTML allows you to:

  • Publish content on websites – Most CMS platforms require HTML for web pages.
  • Enhance styling – HTML supports CSS and JavaScript for advanced formatting and interactivity.
  • Maintain compatibility – HTML is universally supported by browsers, ensuring content displays correctly everywhere.
  • Integrate with web frameworks – Frameworks like React, Vue, and Angular require HTML as the base for rendering components.

Introducing Spire.Doc for Python

Spire.Doc for Python is a robust library for handling multiple document formats. It supports reading and writing Word documents, Markdown files, and exporting content to HTML. The library allows developers to convert Markdown directly to HTML with minimal code, preserving proper formatting and structure.

In addition to HTML, Spire.Doc for Python also allows you to convert Markdown to Word in Python or convert Markdown to PDF in Python, making it particularly useful for developers who want a unified tool for handling Markdown across different output formats.

Benefits of Using Spire.Doc for Python for Markdown to HTML Conversion

  • Easy-to-use API – Simple, intuitive methods that reduce development effort.
  • Accurate formatting – Preserves all Markdown elements such as headings, lists, links, and emphasis in HTML.
  • No extra dependencies – Eliminates the need for manual parsing or third-party libraries.
  • Flexible usage – Supports both single-file conversion and automated batch processing.

Step-by-Step Guide: Converting Markdown to HTML in Python

Now that you understand the purpose and benefits of converting Markdown to HTML, let’s walk through a clear, step-by-step process to transform your Markdown files into structured, web-ready HTML.

Step 1: Install Spire.Doc for Python

First, ensure that Spire.Doc for Python is installed in your environment. You can install it directly from PyPI using pip:

pip install spire.doc

Step 2: Prepare Your Markdown File

Next, create a sample Markdown file that you want to convert. For example, example.md:

Example Markdown File

Step 3: Write the Python Script

Now, write a Python script that loads the Markdown file and converts it to HTML:

from spire.doc import *

# Create a Document object
doc = Document()

# Load the Markdown file
doc.LoadFromFile("example.md", FileFormat.Markdown)

# Save the document as HTML
doc.SaveToFile("example.html", FileFormat.Html)

# Close the document
doc.Close()

Explanation of the code:

  • Document() initializes a new document object.
  • LoadFromFile("example.md", FileFormat.Markdown) loads the Markdown file into memory.
  • SaveToFile("example.html", FileFormat.Html) converts the loaded content into HTML and saves it to disk.
  • doc.Close() ensures resources are released properly, which is particularly important when processing multiple files or running batch operations.

Step 4: Verify the HTML Output

Finally, open the generated example.html file in a web browser or HTML editor. Verify that the Markdown content has been correctly converted.

HTML File Converted from Markdown using Python

Automating Batch Conversion

You can convert multiple Markdown files in a folder automatically:

import os
from spire.doc import *

# Set the folder containing Markdown files
input_folder = "markdown_files"

# Set the folder where HTML files will be saved
output_folder = "html_files"

# Create the output folder if it doesn't exist
os.makedirs(output_folder, exist_ok=True)

# Loop through all files in the input folder
for filename in os.listdir(input_folder):
    # Process only Markdown files
    if filename.endswith(".md"):
        # Create a new Document object for each file
        doc = Document()

        # Load the Markdown file into the Document object
        doc.LoadFromFile(os.path.join(input_folder, filename), FileFormat.Markdown)

        # Construct the output file path by replacing .md extension with .html
        output_file = os.path.join(output_folder, filename.replace(".md", ".html"))

        # Save the loaded Markdown content as HTML
        doc.SaveToFile(output_file, FileFormat.Html)

        # Close the document to release resources
        doc.Close()

This approach allows you to process multiple Markdown files efficiently and generate corresponding HTML files automatically.

Best Practices for Markdown to HTML Conversion

While the basic steps are enough to complete a Markdown-to-HTML conversion, following a few best practices will help you avoid common pitfalls, improve compatibility, and ensure your output is both clean and professional:

  • Use proper Markdown syntax – Ensure headings, lists, links, and emphasis are correctly written.
  • Use UTF-8 Encoding: Always save your Markdown files in UTF-8 encoding to avoid issues with special characters or non-English text.
  • Batch Processing: If you need to convert multiple files, wrap your script in a loop and process entire folders. This saves time and ensures consistent formatting across documents.
  • Enhance Styling: Remember that HTML gives you the flexibility to add CSS and JavaScript for custom layouts, responsive design, and interactivity—something not possible in raw Markdown.

Conclusion

Converting Markdown to HTML using Python with Spire.Doc is simple, reliable, and efficient. It preserves formatting, supports automation, and produces clean HTML output ready for web use. By following this guide, you can implement a smooth Markdown to HTML workflow for both single documents and batch operations.

FAQs

Q1: Can I convert multiple Markdown files to HTML in Python?

A1: Yes, you can automate batch conversions by iterating through Markdown files in a directory and applying the conversion logic to each file.

Q2: Will the HTML preserve all Markdown formatting?

A2: Yes, Spire.Doc effectively preserves all essential Markdown formatting, including headings, lists, bold and italic text, links, and more.

Q3: Is there a way to handle images in Markdown during conversion?

A3: Yes, Spire.Doc supports the conversion of images embedded in Markdown, ensuring they are included in the resulting HTML.

Q4: Do I need additional libraries besides Spire.Doc?

A4: No additional libraries are required. Spire.Doc for Python provides a comprehensive solution for converting Markdown to HTML without any external dependencies.

Q5: Can I use the generated HTML in web frameworks?

A5: Yes, the HTML produced is fully compatible with popular web frameworks such as React, Vue, and Angular, making integration seamless.

Write to Excel in C#

Excel remains one of the most widely used tools for managing and analyzing data due to its powerful features and user-friendly interface. In C# applications, developers often need to generate reports, export database results, or automate tasks by writing directly to Excel files.

To achieve this efficiently, developers often turn to third-party libraries. Spire.XLS for .NET makes it simple to write to Excel programmatically without relying on Microsoft Excel. With Spire.XLS, you can insert text, numbers, dates, formulas, or even bulk datasets such as arrays, DataTables, and lists into Excel worksheets. This provides a fast, flexible, and reliable way to automate Excel writing in C# applications.

On this page:

Getting Started with Spire.XLS for .NET

What’s Spire.XLS for .NET

Spire.XLS for .NET is a professional .NET Excel library developed by E-iceblue. It allows developers to write to Excel files in C# and perform a wide range of operations including creating, editing, reading, and exporting Excel documents—without requiring Microsoft Excel to be installed.

Key features include:

  • Write and update Excel files programmatically.
  • Support for Excel formats (XLS, XLSX, CSV, ODS).
  • Advanced features such as formulas, charts, pivot tables, and data validation.
  • Export Excel to PDF, HTML, and image formats.
  • High performance with large datasets, suitable for desktop, server, and web applications.

How to Install Spire.XLS for .NET

Option 1: Install via NuGet (recommended)

  • Open Visual Studio.
  • Navigate to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
  • Search for Spire.XLS and install it.

Or, install it directly using the Package Manager Console :

PM> Install-Package Spire.XLS

Option 2: Manual installation

Once installed, you’re ready to start writing to Excel in C#.

How to Create a New Excel File in C#

The first step is to create a new workbook and add a worksheet. Here’s how:

using Spire.Xls;

namespace CreateNewExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new workbook
            Workbook workbook = new Workbook();

            // Remove default worksheets
            workbook.Worksheets.Clear();

            // Add a worksheet
            Worksheet sheet = workbook.Worksheets.Add("Report");

            // Save the empty Excel file
            workbook.SaveToFile("NewExcelFile.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

At this point, you have created an empty Excel file with a worksheet named “Report”. Next, let’s write data into it.

Write Different Data Types to Excel Cells in C#

Spire.XLS allows you to write various data types directly to Excel cells. Below are common examples:

Write Text Values

sheet.Range["A1"].Text = "Hello Excel!";

Write Numeric Values

sheet.Range["A2"].NumberValue = 123.45;

Write Date and Time

sheet.Range["A3"].DateTimeValue = DateTime.Now;
sheet.Range["A3"].NumberFormat = "yyyy-mm-dd hh:mm";

Write Boolean Values

sheet.Range["A4"].BooleanValue = true;

Write TimeSpan Values

sheet.Range["A5"].TimeSpanValue = new TimeSpan(2, 30, 0); // 2 hours 30 minutes;
sheet.Range["A5"].NumberFormat = "[h]:mm:ss";

Insert Formulas

sheet.Range["A6"].Formula = "=SUM(A2,100)";

Insert HTML Formatted Strings

string htmlText = "<span style=\"font-family: Times New Roman; color: blue; font-size: 15pt;\">Hello
<strong>Spire.XLS</strong></span>";
sheet.Range["A7"].HtmlString = htmlText;

Write General Values Without Specific Type

sheet.Range["A8"].Value = "General Value";

Output:

C# Write various data types to Excel

You might also be interested in: How to Read Excel Files in C#

Write Bulk Data to Excel Sheets in C#

When dealing with larger datasets, writing values cell by cell isn’t efficient. Spire.XLS provides methods to insert arrays , and DataTables directly. Other data structures can be converted to arrays or DataTables before being written to the Excel sheet.

Write Arrays to Excel

Spire.XLS provides the Worksheet.InsertArray(string[] stringArray, int firstRow, int firstColumn, bool isVertical) method, allowing developers to insert one-dimensional or two-dimensional arrays into a specified range of cells in a worksheet.

string[,] data = {
    { "Name", "Age", "Country" },
    { "Alice", "30", "USA" },
    { "Bob", "28", "UK" },
    { "Charlie", "35", "Canada" }
};
sheet.InsertArray(data, 1, 1);

Output:

Insert Array to Excel in C#

Write DataTables to Excel

To import data from a DataTable to a worksheet, use the Worksheet.InsertDataTable(DataTable dataTable, bool columnHeaders, int firstRow, int firstColumn, bool transTypes) method.

using System.Data;

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Product", typeof(string));
dt.Columns.Add("Price", typeof(double));

// Add rows
dt.Rows.Add(1, "Laptop", 1200.5);
dt.Rows.Add(2, "Tablet", 450.99);
dt.Rows.Add(3, "Phone", 799.0);

// Insert DataTable starting at cell A1
sheet.InsertDataTable(dt, true, 1, 1, true);

Output:

Insert DataTable to Excel in C#

On the contrary, you can export data from Excel to DataTable by using the ExportDataTable method of the Worksheet class.

Write Lists to Excel

While Spire.XLS does not provide a direct method for writing lists to Excel, you can convert lists to a DataTable and then use the InsertDataTable method to write the DataTable to Excel.

using Spire.Xls;
using System.Data;

namespace WriteListToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook instance
            Workbook workbook = new Workbook();

            // Remove default worksheets
            workbook.Worksheets.Clear();

            // Add a worksheet and name it
            Worksheet worksheet = workbook.Worksheets.Add("Students");

            // Create a list with student data
            List<Student> students = new List<Student>
            {
                new Student("Michael", "Johnson", 20, "Computer Science", 3.8),
                new Student("Sarah", "Williams", 22, "Mathematics", 3.6),
                new Student("Jessica", "Brown", 19, "Physics", 3.9),
                new Student("David", "Smith", 21, "Chemistry", 3.7),
                new Student("Emily", "Davis", 23, "Biology", 3.5)
            };

            // Convert the list to DataTable
            DataTable dataTable = ConvertListToDataTable(students);

            // Write DataTable to the worksheet
            worksheet.InsertDataTable(dataTable, true, 1, 1, true);

            // Set column width
            worksheet.AllocatedRange.ColumnWidth = 12;

            // Align content to left
            worksheet.AllocatedRange.HorizontalAlignment = HorizontalAlignType.Left;

            // Save to an Excel file
            workbook.SaveToFile("InsertStudents.xlsx", ExcelVersion.Version2016);

            // Dispose resources
            workbook.Dispose();
        }

        static DataTable ConvertListToDataTable(List<Student> students)
        {
            DataTable dataTable = new DataTable();

            // Add columns
            dataTable.Columns.Add("FirstName", typeof(string));
            dataTable.Columns.Add("LastName", typeof(string));
            dataTable.Columns.Add("Age", typeof(int));
            dataTable.Columns.Add("Major", typeof(string));
            dataTable.Columns.Add("GPA", typeof(double));

            // Add rows
            foreach (var student in students)
            {
                DataRow row = dataTable.NewRow();
                row["FirstName"] = student.FirstName;
                row["LastName"] = student.LastName;
                row["Age"] = student.Age;
                row["Major"] = student.Major;
                row["GPA"] = student.GPA;
                dataTable.Rows.Add(row);
            }

            return dataTable;
        }
    }

    class Student
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Major { get; set; }
        public double GPA { get; set; }

        public Student(string firstName, string lastName, int age, string major, double gpa)
        {
            FirstName = firstName;
            LastName = lastName;
            Age = age;
            Major = major;
            GPA = gpa;
        }
    }
}

Output:

Insert List to Excel in C#

Save and Export Excel Files

After writing data, you’ll want to save or export the Excel file. Spire.XLS supports multiple formats including XLSX, CSV, and PDF .

// Save as XLSX
workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2016);

// Save as CSV
workbook.SaveToFile("Output.csv", ",", Encoding.UTF8);

// Export as PDF
workbook.SaveToFile("Output.pdf", FileFormat.PDF);

For web applications, you can also save to a MemoryStream :

using (MemoryStream ms = new MemoryStream())
{
    workbook.SaveToStream(ms, FileFormat.Version2016);
    // Write to Response in ASP.NET if needed
}

Common Issues and Solutions

1. Incorrect Date or Time Format

Issue: Dates/times appear as serial numbers.

Solution :

  • Apply a proper number format to the cell:
sheet.Range["A1"].DateTimeValue = DateTime.Now;
sheet.Range["A1"].NumberFormat = "yyyy-mm-dd hh:mm";

2. Data Overwriting or Misaligned

Issue : Writing arrays or DataTables overwrites existing data unintentionally.

Solution :

  • Check firstRow and firstColumn parameters in InsertArray() or InsertDataTable().
  • Use separate worksheets or offset ranges if necessary.

3. Large Dataset Performance Issues

Issue : Writing thousands of rows is slow.

Solution :

  • Use bulk writing methods instead of looping cell by cell.
  • Apply styles after inserting data to avoid repeated formatting overhead.

4. Formula Not Calculating Correctly

Issue : Excel formulas inserted via sheet.Range["A1"].Formula do not return expected results.

Solution :

  • Ensure the formula syntax is correct for Excel (e.g., =SUM(A2:A10)).
  • Call workbook.CalculateAllValue() to update all formulas before saving if needed.

Conclusion

Writing to Excel in C# doesn’t have to be complex. With Spire.XLS for .NET , you can seamlessly write different data types—whether individual values or large datasets—into Excel worksheets. The library also provides support for styling, formulas, and advanced formatting, ensuring your Excel files are not only accurate but also presentation-ready.

By using efficient bulk-writing techniques like arrays and DataTables, you can handle both small and large data operations with ease. If your goal is to write to Excel files quickly and reliably , Spire.XLS gives you the tools you need—without the overhead of Microsoft Excel.

FAQs

Q1. Can I write to an existing Excel file with Spire.XLS?

Yes. Use workbook.LoadFromFile("file.xlsx") to open an existing file, then modify and save it.

Q2. Does Spire.XLS require Microsoft Excel to be installed?

No. It’s a standalone library that works without Excel.

Q3. Can Spire.XLS handle large Excel files with thousands of rows?

Yes. It’s optimized for high performance with large datasets.

Q4. How do I format cells while writing data?

You can style cells using properties like font, color, borders, and alignment:

sheet.Range["A1"].Style.Font.IsBold = true;
sheet.Range["A1"].Style.Color = Color.Yellow;
sheet.Range["A1"].Style.HorizontalAlignment  = HorizontalAlignType.Left;

Get a Free License

To fully experience the capabilities of Spire.XLS for .NET without any evaluation limitations, you can request a free 30-day trial license.

Installa con Maven

pip install Spire.Xls

Link Correlati

SXLS to XLSX Conversion: Manual, Online, and Batch Methods

XLS è un vecchio formato di file per fogli di calcolo sviluppato da Microsoft Excel, ed è ancora utilizzato da alcuni utenti oggi. A partire da Excel 2007, Microsoft ha adottato il nuovo formato XLSX. A causa delle differenze tra questi formati, l'apertura di un file XLS in una versione più recente di Excel può talvolta causare problemi di compatibilità, influenzando la modifica e l'elaborazione dei dati. Di conseguenza, eseguire una conversione da XLS a XLSX è diventato un compito comune nella gestione dei fogli di calcolo. Fortunatamente, questo articolo introduce tre metodi semplici ed efficaci per aiutarti a convertire i file XLS in XLSX in modo rapido e semplice.

Esegui la conversione da XLS a XLSX manualmente

Il primo e più semplice modo per convertire XLS in XLSX è la conversione manuale, che funziona meglio quando si ha solo un piccolo numero di file. Questo metodo non richiede alcun software speciale o conoscenza di programmazione, rendendolo ideale per gli utenti che necessitano di una soluzione rapida. Esistono due approcci comuni per la conversione manuale:

  1. Cambia l'estensione del file

Individua il file XLS che desideri convertire, fai clic con il pulsante destro del mouse su di esso e seleziona Rinomina. Sostituisci l'estensione del file da .xls a .xlsx.

  1. Salva con nome

Apri il file di origine in Excel, fai clic sulla scheda File nel menu in alto, quindi seleziona Salva con nome dal pannello di sinistra. Nel menu a discesa Salva come, scegli XLSX e infine fai clic su Salva.

Converti XLS in XLSX manualmente con Microsoft Excel

Converti XLS in XLSX Online

Se trovi le operazioni manuali troppo dispendiose in termini di tempo, poiché richiedono clic ripetuti, puoi utilizzare invece un convertitore online da XLS a XLSX. Un esempio è CloudConvert, uno strumento di conversione file online gratuito. Non solo converte i file dei fogli di calcolo, ma supporta anche documenti di testo, immagini, formati audio e video. Usarlo è semplice: basta seguire questi passaggi:

  1. Vai al sito web e fai clic sul pulsante rosso Seleziona file per scegliere il file che desideri convertire, oppure trascinalo semplicemente sul pulsante.

  2. Una volta caricato il file, fai clic sul pulsante rosso a destra per avviare la conversione.

  3. Attendi qualche secondo. Quando vedi lo stato Completato, fai clic sul pulsante verde Scarica per salvare il file XLSX convertito sul tuo computer.

Questo metodo è ideale quando è necessario convertire rapidamente solo pochi file XLS in XLSX senza installare alcun software.

Converti in blocco XLS in XLSX in modo sicuro

Se devi convertire centinaia o addirittura migliaia di file, i metodi di conversione manuali o online non sono più pratici. Allo stesso modo, se la sicurezza dei dati è una priorità assoluta, l'opzione migliore è eseguire conversioni in blocco localmente con il codice. Questo approccio garantisce che i dati dei tuoi file rimangano completamente al sicuro, poiché non si basa su alcun servizio online.

A tal fine, consigliamo di utilizzare Spire.XLS, una libreria Excel di terze parti professionale che può essere integrata in sistemi aziendali o flussi di lavoro automatizzati, consentendo conversioni su larga scala da XLS a XLSX.

Spire.XLS per Python

L'esempio seguente dimostra come ciò possa essere ottenuto in Python:

from spire.xls import *
from spire.xls.common import *
import os

# Specify the input and output folders
inputFolder = "/input/XLS SAMPLES/"
outputFolder = "/output/TO XLSX/"

# Loop through all .xls files in the input folder
for file in os.listdir(inputFolder):
    if file.endswith(".xls"):
        # Build full file paths
        inputFile = os.path.join(inputFolder, file)
        outputFile = os.path.join(outputFolder, os.path.splitext(file)[0] + ".xlsx")

        # Create a Workbook object
        workbook = Workbook()
        # Load the XLS file
        workbook.LoadFromFile(inputFile)

        # Save as XLSX format
        workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
        workbook.Dispose()

print("Batch conversion completed successfully!")

Ecco un'anteprima che confronta i file di origine con quelli convertiti:

Converti XLS in XLSX in Spire.XLS per Python

Passaggi spiegati:

  • Importa Spire.XLS e i moduli Python.
  • Scorri tutti i file .xls nella cartella di input.
  • Carica ogni file in un oggetto Workbook.
  • Converti XLS in XLSX salvandolo in formato .xlsx tramite il metodo Workbook.saveToFile().

Se vuoi convertire un file XLSX di nuovo in XLS, puoi anche utilizzare il metodo Workbook.saveToFile(). Spire.XLS supporta anche l'uso di questo metodo per convertire file Excel in PDF, immagini e altro ancora.

Domande frequenti sulla conversione da XLS a XLSX

  1. Come salvo il mio file Excel come XLSX?

Puoi salvare un file Excel come XLSX utilizzando la funzione Salva con nome in Excel o utilizzando strumenti di conversione online o programmatici, a seconda del numero di file e delle tue esigenze.

  1. Quando Excel è passato da XLS a XLSX?

Microsoft ha introdotto il formato XLSX a partire da Excel 2007 per sostituire il vecchio formato XLS. XLSX offre prestazioni migliori, dimensioni dei file ridotte e una migliore compatibilità con le moderne funzionalità di Excel.

  1. XLS è la stessa cosa di XLSX?

No. XLS è il vecchio formato di file binario utilizzato in Excel 97-2003, mentre XLSX è il nuovo formato basato su XML introdotto in Excel 2007. Differiscono per struttura, compatibilità e funzionalità supportate.

  1. Gli strumenti online possono convertire XLS in XLSX?

Sì, molti strumenti online ti consentono di convertire file XLS in XLSX. Sono convenienti per un piccolo numero di file ma potrebbero non essere adatti per grandi lotti o dati sensibili.

  1. Qual è il modo migliore per convertire un gran numero di file XLS in XLSX in modo sicuro?

Per centinaia o migliaia di file, o quando la sicurezza dei dati è importante, l'uso di codice con una libreria come Spire.XLS per la conversione in blocco sulla tua macchina locale è il metodo più efficiente e sicuro.

La Conclusione

In sintesi, la conversione da XLS a XLSX può essere gestita in diversi modi a seconda delle tue esigenze. Per una manciata di file, Excel o gli strumenti online possono essere sufficienti. Ma per file su larga scala o sensibili, l'automazione con il codice è la scelta migliore. Sfruttando Spire.XLS, puoi integrare conversioni massive direttamente nel tuo flusso di lavoro, garantendo sia velocità che sicurezza. Sia che tu debba aggiornare file legacy, ottimizzare i processi interni o preparare i dati per i sistemi moderni, Spire.XLS offre una soluzione professionale e flessibile.

LEGGI ANCHE

Converti Excel (XLSX/XLS) in CSV in Python

Python: Converti Excel in PDF facilmente e rapidamente

Converti CSV in Excel (XLSX) in Python – Singolo e in blocco

Python: Converti Excel in SVG automaticamente

Instalar com Maven

pip install Spire.Xls

Links Relacionados

SXLS to XLSX Conversion: Manual, Online, and Batch Methods

XLS é um formato de arquivo de planilha mais antigo desenvolvido pelo Microsoft Excel, e ainda é usado por alguns usuários hoje. Desde o Excel 2007, a Microsoft adotou o formato mais novo, XLSX. Devido às diferenças entre esses formatos, abrir um arquivo XLS em uma versão mais recente do Excel pode, às vezes, causar problemas de compatibilidade, afetando a edição e o processamento de dados. Como resultado, realizar uma conversão de XLS para XLSX tornou-se uma tarefa comum na gestão de planilhas. Felizmente, este artigo apresenta três métodos simples e eficazes para ajudá-lo a converter arquivos XLS para XLSX de forma rápida e fácil.

Realizar a Conversão de XLS para XLSX Manualmente

A primeira e mais direta maneira de converter XLS para XLSX é a conversão manual, que funciona melhor quando você tem apenas um pequeno número de arquivos. Este método не требует nenhum software especial ou conhecimento de programação, tornando-o ideal para usuários que precisam de uma solução rápida. Existem duas abordagens comuns для a conversão manual:

  1. Alterar a extensão do arquivo

Localize o arquivo XLS que deseja converter, clique com o botão direito nele e selecione Renomear. Substitua a extensão do arquivo de .xls para .xlsx.

  1. Salvar Como

Abra o arquivo de origem no Excel, clique na guia Arquivo no menu superior e, em seguida, selecione Salvar Como no painel esquerdo. Na lista suspensa Salvar como tipo, escolha XLSX e, finalmente, clique em Salvar.

Converter XLS para XLSX manualmente com o Microsoft Excel

Converter XLS para XLSX Online

Se você acha as operações manuais muito demoradas, pois exigem cliques repetidos, pode usar um conversor online de XLS para XLSX. Um exemplo é o CloudConvert, uma ferramenta gratuita de conversão de arquivos online. Ele não apenas converte arquivos de planilha, mas também suporta documentos de texto, imagens, áudio e formatos de vídeo. Usá-lo é simples — basta seguir estes passos:

  1. Navegue até o site e clique no botão vermelho Selecionar Arquivo para escolher o arquivo que deseja converter, ou simplesmente arraste e solte-o no botão.

  2. Uma vez que o arquivo for carregado, clique no botão vermelho à direita para iniciar a conversão.

  3. Aguarde alguns segundos. Quando vir o status Concluído, clique no botão verde Baixar para salvar o arquivo XLSX convertido em seu computador.

Este método é ideal quando você só precisa converter alguns arquivos XLS para XLSX rapidamente, sem instalar nenhum software.

Converter em Lote XLS para XLSX com Segurança

Se você precisa converter centenas ou até milhares de arquivos, os métodos de conversão manual ou online não são mais práticos. Da mesma forma, se a segurança dos dados é uma prioridade, a melhor opção é realizar conversões em lote localmente com código. Essa abordagem garante que os dados dos seus arquivos permaneçam completamente seguros, pois не depende de nenhum serviço online.

Para este propósito, recomendamos o uso do Spire.XLS, uma biblioteca profissional de Excel de terceiros que pode ser integrada a sistemas empresariais ou fluxos de trabalho automatizados, permitindo conversões em grande escala de XLS para XLSX.

Spire.XLS para Python

O exemplo a seguir demonstra como isso pode ser alcançado em Python:

from spire.xls import *
from spire.xls.common import *
import os

# Specify the input and output folders
inputFolder = "/input/XLS SAMPLES/"
outputFolder = "/output/TO XLSX/"

# Loop through all .xls files in the input folder
for file in os.listdir(inputFolder):
    if file.endswith(".xls"):
        # Build full file paths
        inputFile = os.path.join(inputFolder, file)
        outputFile = os.path.join(outputFolder, os.path.splitext(file)[0] + ".xlsx")

        # Create a Workbook object
        workbook = Workbook()
        # Load the XLS file
        workbook.LoadFromFile(inputFile)

        # Save as XLSX format
        workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
        workbook.Dispose()

print("Batch conversion completed successfully!")

Aqui está uma prévia comparando os arquivos de origem com os convertidos:

Converter XLS para XLSX no Spire.XLS para Python

Passos explicados:

  • Importar Spire.XLS e módulos Python.
  • Percorrer todos os arquivos .xls na pasta de entrada.
  • Carregar cada arquivo em um objeto Workbook.
  • Converter XLS para XLSX salvando-o no formato .xlsx através do método Workbook.saveToFile().

Se você quiser converter um arquivo XLSX de volta para XLS, você também pode usar o método Workbook.saveToFile(). O Spire.XLS também suporta o uso deste método para converter arquivos do Excel em PDF, imagens e muito mais.

FAQs sobre a Conversão de XLS para XLSX

  1. Como eu salvo meu arquivo do Excel como XLSX?

Você pode salvar um arquivo do Excel como XLSX usando o recurso Salvar Como no Excel ou usando ferramentas de conversão online ou programáticas, dependendo do número de arquivos e de suas necessidades.

  1. Quando o Excel mudou de XLS para XLSX?

A Microsoft introduziu o formato XLSX a partir do Excel 2007 para substituir o formato XLS mais antigo. O XLSX oferece melhor desempenho, tamanho de arquivo reduzido e compatibilidade aprimorada com os recursos modernos do Excel.

  1. XLS é o mesmo que XLSX?

Não. XLS é o formato de arquivo binário mais antigo usado no Excel 97-2003, enquanto XLSX é o formato mais novo baseado em XML introduzido no Excel 2007. Eles diferem em estrutura, compatibilidade e recursos suportados.

  1. As ferramentas online podem converter XLS para XLSX?

Sim, muitas ferramentas online permitem que você converta arquivos XLS para XLSX. Elas são convenientes para um pequeno número de arquivos, mas podem не ser adequadas para grandes lotes ou dados sensíveis.

  1. Qual é a melhor maneira de converter um grande número de arquivos XLS para XLSX com segurança?

Para centenas ou milhares de arquivos, ou quando a segurança dos dados é importante, usar código com uma biblioteca como o Spire.XLS para conversão em lote em sua máquina local é o método mais eficiente e seguro.

A Conclusão

Em resumo, a conversão de XLS para XLSX pode ser tratada de diferentes maneiras, dependendo de suas necessidades. Para um punhado de arquivos, o Excel ou ferramentas online podem ser suficientes. Mas para arquivos em grande escala ou sensíveis, a automação com código é a melhor escolha. Ao aproveitar o Spire.XLS, você pode integrar conversões em massa diretamente em seu fluxo de trabalho, garantindo velocidade e segurança. Seja para atualizar arquivos legados, otimizar processos internos ou preparar dados para sistemas modernos, o Spire.XLS oferece uma solução profissional e flexível.

LEIA TAMBÉM

Converter Excel (XLSX/XLS) para CSV em Python

Python: Converter Excel para PDF de forma fácil e rápida

Converter CSV para Excel (XLSX) em Python – Único e em Lote

Python: Converter Excel para SVG Automaticamente

SXLS to XLSX Conversion: Manual, Online, and Batch Methods

XLS는 Microsoft Excel에서 개발한 오래된 스프레드시트 파일 형식이며, 오늘날에도 일부 사용자들이 사용하고 있습니다. 2007년 Excel부터 Microsoft는 새로운 XLSX 형식을 채택했습니다. 이러한 형식 간의 차이로 인해 최신 버전의 Excel에서 XLS 파일을 열면 호환성 문제가 발생하여 편집 및 데이터 처리에 영향을 줄 수 있습니다. 결과적으로 XLS를 XLSX로 변환하는 것은 스프레드시트 관리에서 일반적인 작업이 되었습니다. 다행히도 이 기사에서는 XLS 파일을 XLSX로 빠르고 쉽게 변환하는 데 도움이 되는 세 가지 간단하고 효과적인 방법을 소개합니다.

수동으로 XLS에서 XLSX로 변환 수행

XLS를 XLSX로 변환하는 첫 번째이자 가장 간단한 방법은 수동 변환이며, 파일 수가 적을 때 가장 효과적입니다. 이 방법은 특별한 소프트웨어나 프로그래밍 지식이 필요하지 않으므로 빠른 해결책이 필요한 사용자에게 이상적입니다. 수동 변환에는 두 가지 일반적인 접근 방식이 있습니다.

  1. 파일 확장자 변경

변환하려는 XLS 파일을 찾아 마우스 오른쪽 버튼으로 클릭하고 이름 바꾸기를 선택합니다. 파일 확장자를 .xls에서 .xlsx로 바꿉니다.

  1. 다른 이름으로 저장

Excel에서 원본 파일을 열고 상단 메뉴의 파일 탭을 클릭한 다음 왼쪽 패널에서 다른 이름으로 저장을 선택합니다. 파일 형식 드롭다운에서 XLSX를 선택하고 마지막으로 저장을 클릭합니다.

Microsoft Excel을 사용하여 수동으로 XLS를 XLSX로 변환

온라인에서 XLS를 XLSX로 변환

반복적인 클릭이 필요하기 때문에 수동 작업이 너무 시간이 많이 걸린다고 생각되면 온라인 XLS-XLSX 변환기를 대신 사용할 수 있습니다. 한 가지 예는 무료 온라인 파일 변환 도구인 CloudConvert입니다. 스프레드시트 파일뿐만 아니라 텍스트 문서, 이미지, 오디오 및 비디오 형식도 지원합니다. 사용 방법은 간단하며 다음 단계를 따르기만 하면 됩니다.

  1. 웹사이트로 이동하여 빨간색 파일 선택 버튼을 클릭하여 변환하려는 파일을 선택하거나 버튼 위로 파일을 끌어다 놓습니다.

  2. 파일이 업로드되면 오른쪽의 빨간색 버튼을 클릭하여 변환을 시작합니다.

  3. 몇 초간 기다립니다. 완료 상태가 표시되면 녹색 다운로드 버튼을 클릭하여 변환된 XLSX 파일을 컴퓨터에 저장합니다.

이 방법은 소프트웨어를 설치하지 않고 몇 개의 XLS 파일을 XLSX로 빠르게 변환해야 할 때 이상적입니다.

안전하게 XLS를 XLSX로 일괄 변환

수백 또는 수천 개의 파일을 변환해야 하는 경우 수동 또는 온라인 변환 방법은 더 이상 실용적이지 않습니다. 마찬가지로 데이터 보안이 최우선 순위인 경우 코드를 사용하여 로컬에서 일괄 변환을 수행하는 것이 최선의 선택입니다. 이 접근 방식은 온라인 서비스에 의존하지 않으므로 파일 데이터가 완전히 안전하게 유지되도록 보장합니다.

이를 위해 엔터프라이즈 시스템이나 자동화된 워크플로에 통합할 수 있는 전문적인 타사 Excel 라이브러리인 Spire.XLS를 사용하는 것을 권장합니다. 이를 통해 대규모 XLS-XLSX 변환이 가능합니다.

Python용 Spire.XLS

다음 예제는 Python에서 이를 어떻게 달성할 수 있는지 보여줍니다.

from spire.xls import *
from spire.xls.common import *
import os

# Specify the input and output folders
inputFolder = "/input/XLS SAMPLES/"
outputFolder = "/output/TO XLSX/"

# Loop through all .xls files in the input folder
for file in os.listdir(inputFolder):
    if file.endswith(".xls"):
        # Build full file paths
        inputFile = os.path.join(inputFolder, file)
        outputFile = os.path.join(outputFolder, os.path.splitext(file)[0] + ".xlsx")

        # Create a Workbook object
        workbook = Workbook()
        # Load the XLS file
        workbook.LoadFromFile(inputFile)

        # Save as XLSX format
        workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
        workbook.Dispose()

print("Batch conversion completed successfully!")

다음은 원본 파일과 변환된 파일을 비교한 미리보기입니다.

Python용 Spire.XLS에서 XLS를 XLSX로 변환

단계 설명:

  • Spire.XLS 및 Python 모듈을 가져옵니다.
  • 입력 폴더의 모든 .xls 파일을 반복합니다.
  • 각 파일을 Workbook 객체에 로드합니다.
  • Workbook.saveToFile() 메서드를 통해 .xlsx 형식으로 저장하여 XLS를 XLSX로 변환합니다.

XLSX 파일을 다시 XLS로 변환하려면 Workbook.saveToFile() 메서드를 사용할 수도 있습니다. Spire.XLS는 이 메서드를 사용하여 Excel 파일을 PDF, 이미지 등으로 변환하는 것도 지원합니다.

XLS에서 XLSX로 변환에 대한 자주 묻는 질문

  1. Excel 파일을 XLSX로 어떻게 저장하나요?

Excel에서 다른 이름으로 저장 기능을 사용하거나 파일 수와 필요에 따라 온라인 또는 프로그래밍 방식의 변환 도구를 사용하여 Excel 파일을 XLSX로 저장할 수 있습니다.

  1. Excel은 언제 XLS에서 XLSX로 전환했나요?

Microsoft는 이전 XLS 형식을 대체하기 위해 Excel 2007부터 XLSX 형식을 도입했습니다. XLSX는 더 나은 성능, 감소된 파일 크기 및 최신 Excel 기능과의 향상된 호환성을 제공합니다.

  1. XLS와 XLSX는 같은 것인가요?

아니요. XLS는 Excel 97-2003에서 사용된 이전 바이너리 파일 형식이며, XLSX는 Excel 2007에서 도입된 최신 XML 기반 형식입니다. 구조, 호환성 및 지원되는 기능이 다릅니다.

  1. 온라인 도구로 XLS를 XLSX로 변환할 수 있나요?

예, 많은 온라인 도구를 사용하여 XLS 파일을 XLSX로 변환할 수 있습니다. 소량의 파일에는 편리하지만 대량 배치나 민감한 데이터에는 적합하지 않을 수 있습니다.

  1. 많은 수의 XLS 파일을 안전하게 XLSX로 변환하는 가장 좋은 방법은 무엇인가요?

수백 또는 수천 개의 파일이나 데이터 보안이 중요한 경우, 로컬 컴퓨터에서 일괄 변환을 위해 Spire.XLS와 같은 라이브러리를 사용하여 코드를 사용하는 것이 가장 효율적이고 안전한 방법입니다.

결론

요약하자면, XLS에서 XLSX로의 변환은 필요에 따라 다른 방식으로 처리할 수 있습니다. 소수의 파일의 경우 Excel이나 온라인 도구로 충분할 수 있습니다. 그러나 대규모 또는 민감한 파일의 경우 코드를 사용한 자동화가 최선의 선택입니다. Spire.XLS를 활용하여 대량 변환을 워크플로에 직접 통합하여 속도와 안전성을 모두 보장할 수 있습니다. 레거시 파일을 업그레이드하거나 내부 프로세스를 간소화하거나 최신 시스템을 위해 데이터를 준비해야 하는 경우 Spire.XLS는 전문적이고 유연한 솔루션을 제공합니다.

함께 읽기

Python에서 Excel(XLSX/XLS)을 CSV로 변환

Python: 쉽고 빠르게 Excel을 PDF로 변환

Python에서 CSV를 Excel(XLSX)로 변환 – 단일 및 일괄

Python: Excel을 SVG로 자동 변환

Installer avec Maven

pip install Spire.Xls

Liens connexes

SXLS to XLSX Conversion: Manual, Online, and Batch Methods

XLS est un ancien format de fichier de tableur développé par Microsoft Excel, et il est encore utilisé par certains utilisateurs aujourd'hui. Depuis Excel 2007, Microsoft a adopté le nouveau format XLSX. En raison des différences entre ces formats, l'ouverture d'un fichier XLS dans une version plus récente d'Excel peut parfois entraîner des problèmes de compatibilité, affectant l'édition et le traitement des données. Par conséquent, effectuer une conversion de XLS en XLSX est devenue une tâche courante dans la gestion des tableurs. Heureusement, cet article présente trois méthodes simples et efficaces pour vous aider à convertir rapidement et facilement des fichiers XLS en XLSX.

Effectuer la conversion de XLS en XLSX manuellement

La première et la plus simple façon de convertir XLS en XLSX est la conversion manuelle, qui fonctionne le mieux lorsque vous n'avez qu'un petit nombre de fichiers. Cette méthode ne nécessite aucun logiciel spécial ni connaissance en programmation, ce qui la rend idéale pour les utilisateurs qui ont besoin d'une solution rapide. Il existe deux approches courantes pour la conversion manuelle :

  1. Changer l'extension du fichier

Localisez le fichier XLS que vous souhaitez convertir, faites un clic droit dessus et sélectionnez Renommer. Remplacez l'extension du fichier de .xls par .xlsx.

  1. Enregistrer sous

Ouvrez le fichier source dans Excel, cliquez sur l'onglet Fichier dans le menu supérieur, puis sélectionnez Enregistrer sous dans le panneau de gauche. Dans le menu déroulant Type de fichier, choisissez XLSX, et enfin cliquez sur Enregistrer.

Convertir XLS en XLSX manuellement avec Microsoft Excel

Convertir XLS en XLSX en ligne

Si vous trouvez les opérations manuelles trop longues, car elles nécessitent des clics répétés, vous pouvez utiliser un convertisseur XLS en XLSX en ligne à la place. Un exemple est CloudConvert, un outil de conversion de fichiers en ligne gratuit. Il ne convertit pas seulement les fichiers de tableur, mais prend également en charge les documents texte, les images, les formats audio et vidéo. Son utilisation est simple — il suffit de suivre ces étapes :

  1. Accédez au site web et cliquez sur le bouton rouge Sélectionner un fichier pour choisir le fichier que vous souhaitez convertir, ou faites-le simplement glisser et déposez-le sur le bouton.

  2. Une fois le fichier téléchargé, cliquez sur le bouton rouge à droite pour démarrer la conversion.

  3. Attendez quelques secondes. Lorsque vous voyez le statut Terminé, cliquez sur le bouton vert Télécharger pour enregistrer le fichier XLSX converti sur votre ordinateur.

Cette méthode est idéale lorsque vous n'avez besoin de convertir que quelques fichiers XLS en XLSX rapidement sans installer de logiciel.

Conversion par lots sécurisée de XLS en XLSX

Si vous devez convertir des centaines, voire des milliers de fichiers, les méthodes de conversion manuelles ou en ligne ne sont plus pratiques. De même, si la sécurité des données est une priorité absolue, la meilleure option est d'effectuer des conversions par lots localement avec du code. Cette approche garantit que les données de vos fichiers restent totalement sécurisées, car elle ne dépend d'aucun service en ligne.

À cette fin, nous vous recommandons d'utiliser Spire.XLS, une bibliothèque Excel tierce professionnelle qui peut être intégrée dans des systèmes d'entreprise ou des flux de travail automatisés, permettant des conversions XLS en XLSX à grande échelle.

Spire.XLS pour Python

L'exemple suivant montre comment cela peut être réalisé en Python :

from spire.xls import *
from spire.xls.common import *
import os

# Specify the input and output folders
inputFolder = "/input/XLS SAMPLES/"
outputFolder = "/output/TO XLSX/"

# Loop through all .xls files in the input folder
for file in os.listdir(inputFolder):
    if file.endswith(".xls"):
        # Build full file paths
        inputFile = os.path.join(inputFolder, file)
        outputFile = os.path.join(outputFolder, os.path.splitext(file)[0] + ".xlsx")

        # Create a Workbook object
        workbook = Workbook()
        # Load the XLS file
        workbook.LoadFromFile(inputFile)

        # Save as XLSX format
        workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
        workbook.Dispose()

print("Batch conversion completed successfully!")

Voici un aperçu comparant les fichiers sources avec les fichiers convertis :

Convertir XLS en XLSX dans Spire.XLS pour Python

Étapes expliquées :

  • Importer Spire.XLS et les modules Python.
  • Parcourir tous les fichiers .xls dans le dossier d'entrée.
  • Charger chaque fichier dans un objet Workbook.
  • Convertir XLS en XLSX en l'enregistrant au format .xlsx via la méthode Workbook.saveToFile().

Si vous souhaitez convertir un fichier XLSX en XLS, vous pouvez également utiliser la méthode Workbook.saveToFile(). Spire.XLS prend également en charge l'utilisation de cette méthode pour convertir des fichiers Excel en PDF, images, et plus encore.

FAQ sur la conversion de XLS en XLSX

  1. Comment puis-je enregistrer mon fichier Excel en tant que XLSX ?

Vous pouvez enregistrer un fichier Excel en tant que XLSX en utilisant la fonction Enregistrer sous dans Excel ou en utilisant des outils de conversion en ligne ou programmatiques, en fonction du nombre de fichiers et de vos besoins.

  1. Quand Excel est-il passé de XLS à XLSX ?

Microsoft a introduit le format XLSX à partir d'Excel 2007 pour remplacer l'ancien format XLS. XLSX offre de meilleures performances, une taille de fichier réduite et une compatibilité améliorée avec les fonctionnalités modernes d'Excel.

  1. XLS est-il identique à XLSX ?

Non. XLS est l'ancien format de fichier binaire utilisé dans Excel 97-2003, tandis que XLSX est le nouveau format basé sur XML introduit dans Excel 2007. Ils diffèrent par leur structure, leur compatibilité et les fonctionnalités prises en charge.

  1. Les outils en ligne peuvent-ils convertir XLS en XLSX ?

Oui, de nombreux outils en ligne vous permettent de convertir des fichiers XLS en XLSX. Ils sont pratiques pour un petit nombre de fichiers mais peuvent ne pas convenir pour de grands lots ou des données sensibles.

  1. Quelle est la meilleure façon de convertir un grand nombre de fichiers XLS en XLSX en toute sécurité ?

Pour des centaines ou des milliers de fichiers, ou lorsque la sécurité des données est importante, l'utilisation de code avec une bibliothèque comme Spire.XLS pour la conversion par lots sur votre machine locale est la méthode la plus efficace et la plus sûre.

La Conclusion

En résumé, la conversion de XLS en XLSX peut être gérée de différentes manières en fonction de vos besoins. Pour une poignée de fichiers, Excel ou les outils en ligne peuvent être suffisants. Mais pour des fichiers à grande échelle ou sensibles, l'automatisation avec du code est le meilleur choix. En tirant parti de Spire.XLS, vous pouvez intégrer des conversions en masse directement dans votre flux de travail, garantissant à la fois vitesse et sécurité. Que vous ayez besoin de mettre à niveau des fichiers hérités, de rationaliser les processus internes ou de préparer des données pour des systèmes modernes, Spire.XLS offre une solution professionnelle et flexible.

LIRE AUSSI

Convertir Excel (XLSX/XLS) en CSV en Python

Python : Convertir Excel en PDF facilement et rapidement

Convertir CSV en Excel (XLSX) en Python – Unique et par lots

Python : Convertir Excel en SVG automatiquement

Instalar con Maven

pip install Spire.Xls

Enlaces Relacionados

SXLS to XLSX Conversion: Manual, Online, and Batch Methods

XLS es un formato de archivo de hoja de cálculo más antiguo desarrollado por Microsoft Excel, y todavía es utilizado por algunos usuarios hoy en día. Desde Excel 2007, Microsoft ha adoptado el formato más nuevo, XLSX. Debido a las diferencias entre estos formatos, abrir un archivo XLS en una versión más reciente de Excel a veces puede causar problemas de compatibilidad, afectando la edición y el procesamiento de datos. Como resultado, realizar una conversión de XLS a XLSX se ha convertido en una tarea común en la gestión de hojas de cálculo. Afortunadamente, este artículo presenta tres métodos simples y efectivos para ayudarlo a convertir archivos XLS a XLSX de manera rápida y fácil.

Realizar la conversión de XLS a XLSX manualmente

La primera y más sencilla forma de convertir XLS a XLSX es la conversión manual, que funciona mejor cuando solo tiene una pequeña cantidad de archivos. Este método no requiere ningún software especial ni conocimientos de programación, lo que lo hace ideal para usuarios que necesitan una solución rápida. Hay dos enfoques comunes para la conversión manual:

  1. Cambiar la extensión del archivo

Ubique el archivo XLS que desea convertir, haga clic derecho sobre él y seleccione Cambiar nombre. Reemplace la extensión del archivo de .xls a .xlsx.

  1. Guardar como

Abra el archivo de origen en Excel, haga clic en la pestaña Archivo en el menú superior y luego seleccione Guardar como en el panel izquierdo. En el menú desplegable Guardar como tipo, elija XLSX y finalmente haga clic en Guardar.

Convertir XLS a XLSX manualmente con Microsoft Excel

Convertir XLS a XLSX en línea

Si encuentra que las operaciones manuales consumen demasiado tiempo, ya que requieren clics repetidos, puede usar un convertidor de XLS a XLSX en línea en su lugar. Un ejemplo es CloudConvert, una herramienta gratuita de conversión de archivos en línea. No solo convierte archivos de hoja de cálculo, sino que también admite documentos de texto, imágenes, audio y formatos de video. Usarlo es sencillo, solo siga estos pasos:

  1. Navegue al sitio web y haga clic en el botón rojo Seleccionar archivo para elegir el archivo que desea convertir, o simplemente arrástrelo y suéltelo en el botón.

  2. Una vez que el archivo se haya cargado, haga clic en el botón rojo de la derecha para iniciar la conversión.

  3. Espere unos segundos. Cuando vea el estado Finalizado, haga clic en el botón verde Descargar para guardar el archivo XLSX convertido en su computadora.

Este método es ideal cuando solo necesita convertir unos pocos archivos XLS a XLSX rápidamente sin instalar ningún software.

Convertir por lotes XLS a XLSX de forma segura

Si necesita convertir cientos o incluso miles de archivos, los métodos de conversión manual o en línea ya no son prácticos. Del mismo modo, si la seguridad de los datos es una prioridad principal, la mejor opción es realizar conversiones por lotes localmente con código. Este enfoque garantiza que los datos de sus archivos permanezcan completamente seguros, ya que no depende de ningún servicio en línea.

Para este propósito, recomendamos usar Spire.XLS, una biblioteca de Excel de terceros profesional que se puede integrar en sistemas empresariales o flujos de trabajo automatizados, permitiendo conversiones de XLS a XLSX a gran escala.

Spire.XLS para Python

El siguiente ejemplo demuestra cómo se puede lograr esto en Python:

from spire.xls import *
from spire.xls.common import *
import os

# Specify the input and output folders
inputFolder = "/input/XLS SAMPLES/"
outputFolder = "/output/TO XLSX/"

# Loop through all .xls files in the input folder
for file in os.listdir(inputFolder):
    if file.endswith(".xls"):
        # Build full file paths
        inputFile = os.path.join(inputFolder, file)
        outputFile = os.path.join(outputFolder, os.path.splitext(file)[0] + ".xlsx")

        # Create a Workbook object
        workbook = Workbook()
        # Load the XLS file
        workbook.LoadFromFile(inputFile)

        # Save as XLSX format
        workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
        workbook.Dispose()

print("Batch conversion completed successfully!")

Aquí hay una vista previa que compara los archivos de origen con los convertidos:

Convertir XLS a XLSX en Spire.XLS para Python

Pasos explicados:

  • Importar Spire.XLS y módulos de Python.
  • Recorrer todos los archivos .xls en la carpeta de entrada.
  • Cargar cada archivo en un objeto Workbook.
  • Convertir XLS a XLSX guardándolo en formato .xlsx a través del método Workbook.saveToFile().

Si desea convertir un archivo XLSX de nuevo a XLS, también puede usar el método Workbook.saveToFile(). Spire.XLS también admite el uso de este método para convertir archivos de Excel a PDF, imágenes y más.

Preguntas frecuentes sobre la conversión de XLS a XLSX

  1. ¿Cómo guardo mi archivo de Excel como XLSX?

Puede guardar un archivo de Excel como XLSX usando la función Guardar como en Excel o usando herramientas de conversión en línea o programáticas, dependiendo de la cantidad de archivos y sus necesidades.

  1. ¿Cuándo cambió Excel de XLS a XLSX?

Microsoft introdujo el formato XLSX a partir de Excel 2007 para reemplazar el antiguo formato XLS. XLSX ofrece un mejor rendimiento, un tamaño de archivo reducido y una compatibilidad mejorada con las funciones modernas de Excel.

  1. ¿Es XLS lo mismo que XLSX?

No. XLS es el antiguo formato de archivo binario utilizado en Excel 97-2003, mientras que XLSX es el formato más nuevo basado en XML introducido en Excel 2007. Difieren en estructura, compatibilidad y características admitidas.

  1. ¿Pueden las herramientas en línea convertir XLS a XLSX?

Sí, muchas herramientas en línea le permiten convertir archivos XLS a XLSX. Son convenientes para un número reducido de archivos, pero pueden no ser adecuadas para grandes lotes o datos confidenciales.

  1. ¿Cuál es la mejor manera de convertir una gran cantidad de archivos XLS a XLSX de forma segura?

Para cientos o miles de archivos, o cuando la seguridad de los datos es importante, usar código con una biblioteca como Spire.XLS para la conversión por lotes en su máquina local es el método más eficiente y seguro.

La Conclusión

En resumen, la conversión de XLS a XLSX se puede manejar de diferentes maneras según sus necesidades. Para un puñado de archivos, Excel o las herramientas en línea pueden ser suficientes. Pero para archivos a gran escala o confidenciales, la automatización con código es la mejor opción. Al aprovechar Spire.XLS, puede integrar conversiones masivas directamente en su flujo de trabajo, garantizando tanto la velocidad como la seguridad. Ya sea que necesite actualizar archivos heredados, optimizar procesos internos o preparar datos para sistemas modernos, Spire.XLS ofrece una solución profesional y flexible.

TAMBIÉN LEA

Convertir Excel (XLSX/XLS) a CSV en Python

Python: Convertir Excel a PDF de forma fácil y rápida

Convertir CSV a Excel (XLSX) en Python – Individual y por lotes

Python: Convertir Excel a SVG automáticamente

Mit Maven installieren

pip install Spire.Xls

Verwandte Links

SXLS to XLSX Conversion: Manual, Online, and Batch Methods

XLS ist ein älteres Tabellenkalkulationsdateiformat, das von Microsoft Excel entwickelt wurde und heute noch von einigen Benutzern verwendet wird. Seit Excel 2007 hat Microsoft das neuere XLSX-Format eingeführt. Aufgrund der Unterschiede zwischen diesen Formaten kann das Öffnen einer XLS-Datei in einer neueren Version von Excel manchmal zu Kompatibilitätsproblemen führen, die die Bearbeitung und Datenverarbeitung beeinträchtigen. Daher ist die Durchführung einer XLS-zu-XLSX-Konvertierung zu einer häufigen Aufgabe in der Tabellenkalkulationsverwaltung geworden. Glücklicherweise stellt dieser Artikel drei einfache und effektive Methoden vor, mit denen Sie XLS-Dateien schnell und einfach in XLSX konvertieren können.

XLS-zu-XLSX-Konvertierung manuell durchführen

Die erste und einfachste Möglichkeit, XLS in XLSX zu konvertieren, ist die manuelle Konvertierung, die am besten funktioniert, wenn Sie nur eine geringe Anzahl von Dateien haben. Diese Methode erfordert keine spezielle Software oder Programmierkenntnisse und ist daher ideal für Benutzer, die eine schnelle Lösung benötigen. Es gibt zwei gängige Ansätze für die manuelle Konvertierung:

  1. Dateierweiterung ändern

Suchen Sie die XLS-Datei, die Sie konvertieren möchten, klicken Sie mit der rechten Maustaste darauf und wählen Sie Umbenennen. Ersetzen Sie die Dateierweiterung von .xls durch .xlsx.

  1. Speichern unter

Öffnen Sie die Quelldatei in Excel, klicken Sie im oberen Menü auf die Registerkarte Datei und wählen Sie dann im linken Bereich Speichern unter. Wählen Sie im Dropdown-Menü Dateityp XLSX aus und klicken Sie abschließend auf Speichern.

XLS manuell mit Microsoft Excel in XLSX konvertieren

XLS online in XLSX konvertieren

Wenn Ihnen manuelle Operationen zu zeitaufwändig sind, da sie wiederholte Klicks erfordern, können Sie stattdessen einen Online-XLS-zu-XLSX-Konverter verwenden. Ein Beispiel ist CloudConvert, ein kostenloses Online-Tool zur Dateikonvertierung. Es konvertiert nicht nur Tabellenkalkulationsdateien, sondern unterstützt auch Textdokumente, Bilder, Audio- und Videoformate. Die Verwendung ist unkompliziert – folgen Sie einfach diesen Schritten:

  1. Navigieren Sie zur Website und klicken Sie auf die rote Schaltfläche Datei auswählen, um die zu konvertierende Datei auszuwählen, oder ziehen Sie sie einfach per Drag & Drop auf die Schaltfläche.

  2. Sobald die Datei hochgeladen ist, klicken Sie auf die rote Schaltfläche auf der rechten Seite, um die Konvertierung zu starten.

  3. Warten Sie einige Sekunden. Wenn Sie den Status Fertig sehen, klicken Sie auf die grüne Schaltfläche Herunterladen, um die konvertierte XLSX-Datei auf Ihrem Computer zu speichern.

Diese Methode ist ideal, wenn Sie nur wenige XLS-Dateien schnell in XLSX konvertieren müssen, ohne Software zu installieren.

XLS sicher stapelweise in XLSX konvertieren

Wenn Sie Hunderte oder sogar Tausende von Dateien konvertieren müssen, sind manuelle oder Online-Konvertierungsmethoden nicht mehr praktikabel. Wenn die Datensicherheit oberste Priorität hat, ist die beste Option, Stapelkonvertierungen lokal mit Code durchzuführen. Dieser Ansatz stellt sicher, dass Ihre Dateidaten vollständig sicher bleiben, da er nicht auf einen Online-Dienst angewiesen ist.

Zu diesem Zweck empfehlen wir die Verwendung von Spire.XLS, einer professionellen Excel-Bibliothek von Drittanbietern, die in Unternehmenssysteme oder automatisierte Arbeitsabläufe integriert werden kann und groß angelegte XLS-zu-XLSX-Konvertierungen ermöglicht.

Spire.XLS für Python

Das folgende Beispiel zeigt, wie dies in Python erreicht werden kann:

from spire.xls import *
from spire.xls.common import *
import os

# Specify the input and output folders
inputFolder = "/input/XLS SAMPLES/"
outputFolder = "/output/TO XLSX/"

# Loop through all .xls files in the input folder
for file in os.listdir(inputFolder):
    if file.endswith(".xls"):
        # Build full file paths
        inputFile = os.path.join(inputFolder, file)
        outputFile = os.path.join(outputFolder, os.path.splitext(file)[0] + ".xlsx")

        # Create a Workbook object
        workbook = Workbook()
        # Load the XLS file
        workbook.LoadFromFile(inputFile)

        # Save as XLSX format
        workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
        workbook.Dispose()

print("Batch conversion completed successfully!")

Hier ist eine Vorschau, die die Quelldateien mit den konvertierten vergleicht:

XLS in XLSX in Spire.XLS für Python konvertieren

Schritte erklärt:

  • Importieren Sie Spire.XLS und Python-Module.
  • Durchlaufen Sie alle .xls-Dateien im Eingabeordner.
  • Laden Sie jede Datei in ein Workbook-Objekt.
  • Konvertieren Sie XLS in XLSX, indem Sie es im .xlsx-Format über die Methode Workbook.saveToFile() speichern.

Wenn Sie eine XLSX-Datei zurück in XLS konvertieren möchten, können Sie auch die Methode Workbook.saveToFile() verwenden. Spire.XLS unterstützt auch die Verwendung dieser Methode, um Excel-Dateien in PDF, Bilder und mehr zu konvertieren.

FAQs zur XLS-zu-XLSX-Konvertierung

  1. Wie speichere ich meine Excel-Datei als XLSX?

Sie können eine Excel-Datei als XLSX speichern, indem Sie die Funktion Speichern unter in Excel verwenden oder Online- oder programmatische Konvertierungstools nutzen, je nach Anzahl der Dateien und Ihren Anforderungen.

  1. Wann hat Excel von XLS auf XLSX umgestellt?

Microsoft führte das XLSX-Format ab Excel 2007 ein, um das ältere XLS-Format zu ersetzen. XLSX bietet eine bessere Leistung, eine geringere Dateigröße und eine verbesserte Kompatibilität mit modernen Excel-Funktionen.

  1. Ist XLS dasselbe wie XLSX?

Nein. XLS ist das ältere binäre Dateiformat, das in Excel 97-2003 verwendet wurde, während XLSX das neuere XML-basierte Format ist, das in Excel 2007 eingeführt wurde. Sie unterscheiden sich in Struktur, Kompatibilität und unterstützten Funktionen.

  1. Können Online-Tools XLS in XLSX konvertieren?

Ja, viele Online-Tools ermöglichen die Konvertierung von XLS-Dateien in XLSX. Sie sind praktisch für eine kleine Anzahl von Dateien, eignen sich jedoch möglicherweise nicht für große Stapel oder sensible Daten.

  1. Was ist der beste Weg, eine große Anzahl von XLS-Dateien sicher in XLSX zu konvertieren?

Für Hunderte oder Tausende von Dateien oder wenn die Datensicherheit wichtig ist, ist die Verwendung von Code mit einer Bibliothek wie Spire.XLS für die Stapelkonvertierung auf Ihrem lokalen Computer die effizienteste und sicherste Methode.

Das Fazit

Zusammenfassend lässt sich sagen, dass die Konvertierung von XLS in XLSX je nach Ihren Anforderungen auf unterschiedliche Weise gehandhabt werden kann. Für eine Handvoll Dateien können Excel oder Online-Tools ausreichen. Aber für große oder sensible Dateien ist die Automatisierung mit Code die beste Wahl. Durch die Nutzung von Spire.XLS können Sie Massenkonvertierungen direkt in Ihren Arbeitsablauf integrieren und so sowohl Geschwindigkeit als auch Sicherheit gewährleisten. Ob Sie Legacy-Dateien aktualisieren, interne Prozesse optimieren oder Daten für moderne Systeme vorbereiten müssen, Spire.XLS bietet eine professionelle und flexible Lösung.

AUCH LESEN

Excel (XLSX/XLS) in CSV in Python konvertieren

Python: Excel einfach und schnell in PDF konvertieren

CSV in Excel (XLSX) in Python konvertieren – Einzeln & Stapelweise

Python: Excel automatisch in SVG konvertieren

SXLS to XLSX Conversion: Manual, Online, and Batch Methods

XLS — это устаревший формат файлов электронных таблиц, разработанный Microsoft Excel, который до сих пор используется некоторыми пользователями. Начиная с Excel 2007, Microsoft перешла на новый формат XLSX. Из-за различий между этими форматами открытие файла XLS в более новой версии Excel иногда может вызывать проблемы совместимости, влияющие на редактирование и обработку данных. В результате выполнение преобразования XLS в XLSX стало обычной задачей в управлении электронными таблицами. К счастью, в этой статье представлены три простых и эффективных метода, которые помогут вам быстро и легко конвертировать файлы XLS в XLSX.

Выполните преобразование XLS в XLSX вручную

Первый и самый простой способ конвертировать XLS в XLSX — это ручное преобразование, которое лучше всего подходит, когда у вас небольшое количество файлов. Этот метод не требует специального программного обеспечения или знаний в области программирования, что делает его идеальным для пользователей, которым нужно быстрое решение. Существует два распространенных подхода к ручному преобразованию:

  1. Изменить расширение файла

Найдите файл XLS, который вы хотите преобразовать, щелкните по нему правой кнопкой мыши и выберите Переименовать. Замените расширение файла с .xls на .xlsx.

  1. Сохранить как

Откройте исходный файл в Excel, нажмите на вкладку Файл в верхнем меню, затем выберите Сохранить как на левой панели. В выпадающем списке Тип файла выберите XLSX и, наконец, нажмите Сохранить.

Преобразование XLS в XLSX вручную с помощью Microsoft Excel

Конвертировать XLS в XLSX онлайн

Если ручные операции кажутся вам слишком трудоемкими, так как они требуют повторных кликов, вы можете воспользоваться онлайн-конвертером XLS в XLSX. Одним из примеров является CloudConvert, бесплатный онлайн-инструмент для конвертации файлов. Он не только конвертирует файлы электронных таблиц, но и поддерживает текстовые документы, изображения, аудио- и видеоформаты. Использовать его просто — следуйте этим шагам:

  1. Перейдите на веб-сайт и нажмите красную кнопку Выбрать файл, чтобы выбрать файл, который вы хотите преобразовать, или просто перетащите его на кнопку.

  2. После загрузки файла нажмите красную кнопку справа, чтобы начать преобразование.

  3. Подождите несколько секунд. Когда вы увидите статус Завершено, нажмите зеленую кнопку Скачать, чтобы сохранить преобразованный файл XLSX на ваш компьютер.

Этот метод идеален, когда вам нужно быстро преобразовать несколько файлов XLS в XLSX без установки какого-либо программного обеспечения.

Безопасное пакетное преобразование XLS в XLSX

Если вам нужно преобразовать сотни или даже тысячи файлов, ручные или онлайн-методы преобразования уже непрактичны. Аналогично, если безопасность данных является главным приоритетом, лучшим вариантом будет выполнение пакетных преобразований локально с помощью кода. Этот подход гарантирует, что данные ваших файлов останутся в полной безопасности, так как он не зависит от какого-либо онлайн-сервиса.

Для этой цели мы рекомендуем использовать Spire.XLS, профессиональную стороннюю библиотеку Excel, которую можно интегрировать в корпоративные системы или автоматизированные рабочие процессы, что позволяет выполнять крупномасштабные преобразования XLS в XLSX.

Spire.XLS для Python

Следующий пример демонстрирует, как это можно сделать на Python:

from spire.xls import *
from spire.xls.common import *
import os

# Specify the input and output folders
inputFolder = "/input/XLS SAMPLES/"
outputFolder = "/output/TO XLSX/"

# Loop through all .xls files in the input folder
for file in os.listdir(inputFolder):
    if file.endswith(".xls"):
        # Build full file paths
        inputFile = os.path.join(inputFolder, file)
        outputFile = os.path.join(outputFolder, os.path.splitext(file)[0] + ".xlsx")

        # Create a Workbook object
        workbook = Workbook()
        # Load the XLS file
        workbook.LoadFromFile(inputFile)

        # Save as XLSX format
        workbook.SaveToFile(outputFile, ExcelVersion.Version2016)
        workbook.Dispose()

print("Batch conversion completed successfully!")

Вот предварительный просмотр, сравнивающий исходные файлы с преобразованными:

Преобразование XLS в XLSX в Spire.XLS для Python

Объяснение шагов:

  • Импортируйте Spire.XLS и модули Python.
  • Пройдитесь циклом по всем файлам .xls во входной папке.
  • Загрузите каждый файл в объект Workbook.
  • Преобразуйте XLS в XLSX, сохранив его в формате .xlsx с помощью метода Workbook.saveToFile().

Если вы хотите преобразовать файл XLSX обратно в XLS, вы также можете использовать метод Workbook.saveToFile(). Spire.XLS также поддерживает использование этого метода для преобразования файлов Excel в PDF, изображения и многое другое.

Часто задаваемые вопросы о преобразовании XLS в XLSX

  1. Как сохранить мой файл Excel в формате XLSX?

Вы можете сохранить файл Excel в формате XLSX, используя функцию Сохранить как в Excel или с помощью онлайн-инструментов или программных средств преобразования, в зависимости от количества файлов и ваших потребностей.

  1. Когда Excel перешел с XLS на XLSX?

Microsoft представила формат XLSX, начиная с Excel 2007, для замены старого формата XLS. XLSX предлагает лучшую производительность, уменьшенный размер файла и улучшенную совместимость с современными функциями Excel.

  1. XLS — это то же самое, что и XLSX?

Нет. XLS — это старый двоичный формат файлов, использовавшийся в Excel 97-2003, тогда как XLSX — это новый формат на основе XML, представленный в Excel 2007. Они различаются по структуре, совместимости и поддерживаемым функциям.

  1. Могут ли онлайн-инструменты конвертировать XLS в XLSX?

Да, многие онлайн-инструменты позволяют конвертировать файлы XLS в XLSX. Они удобны для небольшого количества файлов, но могут не подходить для больших партий или конфиденциальных данных.

  1. Какой лучший способ безопасно преобразовать большое количество файлов XLS в XLSX?

Для сотен или тысяч файлов, или когда важна безопасность данных, использование кода с библиотекой, такой как Spire.XLS для пакетного преобразования на вашем локальном компьютере, является наиболее эффективным и безопасным методом.

Заключение

В итоге, преобразование XLS в XLSX можно выполнить различными способами в зависимости от ваших потребностей. Для небольшого количества файлов может быть достаточно Excel или онлайн-инструментов. Но для крупномасштабных или конфиденциальных файлов лучшим выбором является автоматизация с помощью кода. Используя Spire.XLS, вы можете интегрировать массовые преобразования непосредственно в свой рабочий процесс, обеспечивая как скорость, так и безопасность. Независимо от того, нужно ли вам обновить устаревшие файлы, оптимизировать внутренние процессы или подготовить данные для современных систем, Spire.XLS предлагает профессиональное и гибкое решение.

ТАКЖЕ ЧИТАЙТЕ

Преобразование Excel (XLSX/XLS) в CSV на Python

Python: Преобразование Excel в PDF легко и быстро

Преобразование CSV в Excel (XLSX) на Python — одиночное и пакетное

Python: Автоматическое преобразование Excel в SVG

Create PDF in ASP.NET Core

Creating PDFs in ASP.NET applications is a common requirement, whether you're generating invoices, reports, forms, or exporting dynamic content. To streamline this process, you can utilize Spire.PDF for .NET, a professional and lightweight library that enables developers to easily create and manipulate PDF documents programmatically, without the need for complex APIs or third-party printer drivers.

In this tutorial, we’ll show you how to create PDF documents in an ASP.NET Core Web application using Spire.PDF for .NET, with examples of creating a PDF from scratch and converting HTML to PDF.

On this page:

Why Use Spire.PDF for .NET?

There are many ways to create PDF in ASP.NET, but most involve trade-offs: some depend on printer drivers, others have limited layout control, and many require heavy third-party frameworks. Spire.PDF for .NET offers a more streamlined approach. It’s a dedicated .NET library that handles the majority of PDF creation and manipulation tasks on its own, without external tools.

Key advantages include:

  • No Adobe dependency – Generate and manage PDFs without Acrobat installed.
  • Full-featured PDF toolkit – Beyond creation, you can edit, merge, split, protect, or annotate PDFs.
  • High-fidelity rendering – Preserve fonts, CSS, images, and layouts when exporting content.
  • ASP.NET ready – Compatible with both ASP.NET Web Forms/MVC and ASP.NET Core projects.
  • Flexible generation options – Create PDFs from scratch, images, or streams.

(Note: HTML-to-PDF conversion requires a lightweight external plugin such as Qt WebEngine.)

Step-by-Step: Generate PDF in ASP.NET Core Web App

Step 1. Create a New ASP.NET Core Web App

  • Open Visual Studio .
  • Select Create a new project .
  • Choose ASP.NET Core Web App (Model-View-Controller) → Click Next .
  • Enter a project name, e.g., PdfDemoApp.
  • Select your target framework (e.g., . NET 6 , 7 , or 8 ).
  • Click Create .

Step 2. Install Spire.PDF via NuGet

  • Right-click on your project → Manage NuGet Packages .
  • Search for Spire.PDF .
  • Install the package Spire.PDF (latest stable version).

Or install using the Package Manager Console :

Install-Package Spire.PDF

Step 3. Add a Controller for PDF Generation

  • Right-click on the Controllers folder → Add → Controller → MVC Controller – Empty .
  • Name it: PdfController.cs.
  • Replace the default code with this:
using Microsoft.AspNetCore.Mvc;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfDemoApp.Controllers
{
    public class PdfController : Controller
    {
        public IActionResult CreatePdf()
        {
            // Create a new PDF document
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));

            // Draw text on the page
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 25f);
            PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
            page.Canvas.DrawString("Hello from ASP.NET Core!", font, brush, 10, 50);

            // Save to memory stream
            using (MemoryStream ms = new MemoryStream())
            {
                doc.SaveToStream(ms);
                doc.Close();
                ms.Position = 0;

                // Return PDF file
                return File(ms.ToArray(), "application/pdf", "Generated.pdf");
            }
        }
    }
}

Step 4: (Optional) Add a Button or Link in Your View

Open Views/Home/Index.cshtml (or whichever view is your homepage).

Add a button or link like this:

<div>
    <a asp-controller="Pdf" asp-action="CreatePdf" class="btn btn-primary">
        Create PDF from Scratch
    </a>
</div>

This uses ASP.NET Core tag helpers to generate the correct route (/Pdf/CreatePdf).

Step 5. Run and Test

  • Press F5 to run your app.
  • On the home page, click the "Create PDF from Scratch" button. This will call the CreatePdf method in PdfController and trigger a download of the generated PDF.
  • If you didn’t add the button, you can still run the CreatePdf method directly by visiting this URL in your browser:

https://localhost:xxxx/Pdf/CreatePdf

(where xxxx is your local port number).

Output:

Create PDF from ASP.NET Core

In addition to text, Spire.PDF supports adding a wide range of elements to PDF, such as images, shapes, tables, lists, hyperlinks, annotations, and watermarks. For more details and advanced usage, check the .NET PDF Tutorials.

Create PDF from HTML in ASP.NET Core

Spire.PDF allows you to convert HTML content directly into PDF files. This feature is particularly useful for generating invoices, reports, receipts, or exporting styled web pages with consistent formatting.

To render HTML as PDF, Spire.PDF relies on an external rendering engine. You can choose between Qt WebEngine or Google Chrome . In this guide, we’ll use Qt WebEngine .

Setup the Qt plugin:

  1. Download the Qt WebEngine plugin for your operating system:

  2. Extract the package to obtain the plugins directory, e.g.: C:\plugins-windows-x64\plugins

  3. Register the plugin path inyour code:

HtmlConverter.PluginPath = @"C:\plugins-windows-x64\plugins";

Once the plugin is ready, you can follow the steps from the previous section and add the code snippet below to your controller to generate PDF output from HTML content.

using Microsoft.AspNetCore.Mvc;
using Spire.Additions.Qt;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfDemoApp.Controllers
{
    public class PdfController : Controller
    {
        [HttpGet]
        public IActionResult HtmlToPdf()
        {
            // Example HTML string
            string html = @"
                <html>
                  <head>
                    <style>
                      body { font-family: Arial, sans-serif; }
                      h1 { color: #2563eb; }
                    </style>
                  </head>
                  <body>
                    <h1>ASP.NET Core: Create PDF from HTML</h1>
                    <p>This PDF was generated using the Qt-based converter.</p>
                  </body>
                </html>";

            // Path to the Qt plugin folder
            // ⚠️ Ensure this folder exists on your server/deployment environment
            string pluginPath = @"C:\plugins-windows-x64\plugins";
            HtmlConverter.PluginPath = pluginPath;

            // Create a temp file path (on server side)
            string tempFile = Path.GetTempFileName();

            // Convert HTML string → PDF using Qt
            HtmlConverter.Convert(
                html,
                tempFile,
                enableJavaScript: true,
                timeout: 100000,                        // milliseconds
                pageSize: new SizeF(595, 842),          // A4 page size in points
                margins: new PdfMargins(40),            // 40pt margins
                LoadHtmlType.SourceCode                 // Load from HTML string
            );

            // Read the generated PDF into memory
            byte[] fileBytes = System.IO.File.ReadAllBytes(tempFile);

            // Clean up temp file
            System.IO.File.Delete(tempFile);

            // Return PDF to browser as download
            return File(fileBytes, "application/pdf", "HtmlToPdf.pdf");
        }
    }
}

Output:

Create PDF from HTML ASP.NET

This example converts inline HTML into a properly formatted PDF. You can also load external HTML files or URLs - see our detailed guide on Convert HTML to PDF in C# for more information.

Best Practices for ASP.NET PDF Generation

  • Use memory streams instead of disk storage for performance and scalability.
  • Cache static PDFs (like terms & conditions or forms) to reduce server load.
  • Use HTML-to-PDF for dynamic reports with CSS styling.
  • Consider templates (like Word-to-PDF with Spire.Doc) when documents have complex layouts.
  • Secure sensitive PDFs with password protection or access permissions.

Conclusion

With Spire.PDF for .NET, you can easily generate PDF in ASP.NET Core applications. Whether you’re creating PDFs from scratch or performing HTML-to-PDF conversion in C# , Spire.PDF provides a reliable, developer-friendly solution—no external dependencies required.

If you also need to generate PDFs from Word documents, that feature is available via Spire.Doc for .NET, another product in the Spire family. Together, they cover the full range of PDF document generation scenarios.

By integrating these tools, developers can streamline workflows, reduce reliance on Adobe or other third-party components, and ensure consistent, professional-quality output. This makes your ASP.NET PDF solutions more scalable, maintainable, and ready for enterprise use.

FAQs

Q1. Do I need Adobe Acrobat installed on the server?

No. Spire.PDF is a standalone library and works independently of Adobe Acrobat.

Q2. Can I generate PDFs from both raw content and HTML?

Yes. You can build documents programmatically (drawing text, shapes, tables) or convert HTML pages to PDF.

Q3. Can I convert Word documents to PDF with Spire.PDF?

No. Word-to-PDF is supported by Spire.Doc for .NET, not Spire.PDF. You can use them together if your project requires it.

Q4. How can I protect generated PDFs?

Spire.PDF supports setting passwords, permissions, and digital signatures for document security.

Q5. Does Spire.PDF support ASP.NET Framework?

Yes. It works with both ASP.NET Core and ASP.NET Framework.

Get a Free License

To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.

Page 2 of 46