C# Convert PDF to JPG

Working with PDF documents is a common requirement in modern applications. Whether you are building a document management system , an ASP.NET web service , or a desktop viewer application , there are times when you need to display a PDF page as an image. Instead of embedding the full PDF viewer, you can convert PDF pages to JPG images and use them wherever images are supported.

In this guide, we will walk through a step-by-step tutorial on how to convert PDF files to JPG images using Spire.PDF for .NET. We’ll cover the basics of converting a single page, handling multiple pages, adjusting resolution and quality, saving images to streams, and even batch converting entire folders of PDFs.

By the end, you’ll have a clear understanding of how to implement PDF-to-image conversion in your .NET projects.

Table of Contents:

Install .NET PDF-to-JPG Converter Library

To perform the conversion, we’ll use Spire.PDF for .NET , a library designed for developers who need full control over PDFs in C#. It supports reading, editing, and converting PDFs without requiring Adobe Acrobat or any third-party dependencies.

Installation via NuGet

You can install Spire.PDF directly into your project using NuGet Package Manager Console:

Install-Package Spire.PDF

Alternatively, open NuGet Package Manager in Visual Studio, search for Spire.PDF , and click Install.

Licensing Note

Spire.PDF offers a free version with limitations, allowing conversion of only the first few pages. For production use, a commercial license unlocks the full feature set.

Core Method: SaveAsImage

The heart of PDF-to-image conversion in Spire.PDF lies in the SaveAsImage() method provided by the PdfDocument class.

Here’s what you need to know:

  • Syntax (overload 1):

  • Image SaveAsImage(int pageIndex, PdfImageType imageType);

    • pageIndex: The zero-based index of the PDF page you want to convert.
    • imageType: The type of image to generate, typically PdfImageType.Bitmap.
  • Syntax (overload 2 with resolution):

  • Image SaveAsImage(int pageIndex, PdfImageType imageType, int dpiX, int dpiY);

    • dpiX, dpiY: Horizontal and vertical resolution (dots per inch).

    Higher DPI = better quality but larger file size.

Supported PdfImageType Values

  • Bitmap → returns a raw image.
  • Metafile → returns a vector image (less common for JPG export).

Most developers use Bitmap when exporting to JPG.

Steps to Convert PDF to JPG in C# .NET

  1. Import the Spire.Pdf and System.Drawing namespaces.
  2. Create a new PdfDocument instance.
  3. Load the PDF file from the specified path.
  4. Use SaveAsImage() to convert one or more pages into images.
  5. Save the generated image(s) in JPG format.

Convert a Single Page to JPG

Here’s a simple workflow to convert a single PDF page to a JPG image:

using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing.Imaging;
using System.Drawing;

namespace ConvertSpecificPageToPng
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a sample PDF document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            // Convert a specific page to a bitmap image
            Image image = doc.SaveAsImage(0, PdfImageType.Bitmap);

            // Save the image as a JPG file
            image.Save("ToJPG.jpg", ImageFormat.Jpeg);

            // Disposes resources
            doc.Dispose();
        }
    }
}

Output:

Convert a single PDF page to JPG

Spire.PDF supports converting PDF to various other image formats like PNG, BMP, SVG, and TIFF. For more details, refer to the documentation: Convert PDF to Image in C#.

Convert Multiple Pages (All or Range)

Convert All Pages

The following loop iterates over all pages, converts each one into an image, and saves it to disk with page numbers in the filename.

for (int i = 0; i < doc.Pages.Count; i++)
{
    Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
    string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
    image.Save(fileName, ImageFormat.Jpeg);
}

Convert a Range of Pages

To convert a specific range of pages (e.g., pages 2 to 4), modify the for loop as follows:

for (int i = 1; i <= 3; i++)
{
    Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
    string fileName = string.Format("Output\\ToJPG-{0}.jpg", i);
    image.Save(fileName, ImageFormat.Jpeg);
}

Advanced Conversion Options

Set Image Resolution/Quality

By default, the output resolution might be too low for printing or detailed analysis. You can set DPI explicitly:

Image image = doc.SaveAsImage(0, PdfImageType.Bitmap, 300, 300);
image.Save("ToJPG.jpg", ImageFormat.Jpeg);

Tips:

  • 72 DPI : Default, screen quality.
  • 150 DPI : Good for previews and web.
  • 300 DPI : High quality, suitable for printing.

Higher DPI results in sharper images but also increases memory and file size.

Save the Converted Images as Stream

Instead of writing directly to disk, you can store the output in memory streams. This is useful in:

  • ASP.NET applications returning images to browsers.
  • Web APIs sending images as HTTP responses.
  • Database storage for binary blobs.
using (MemoryStream ms = new MemoryStream())
{
    pdf.SaveAsImage(0, PdfImageType.Bitmap, 300, 300).Save(ms, ImageFormat.Jpeg);
    byte[] imageBytes = ms.ToArray();
}

Here, the JPG image is stored as a byte array , ready for further processing.

Batch Conversion (Multiple PDFs)

In scenarios where you need to process multiple PDF documents at once, you can apply batch conversion as shown below:

string[] files = Directory.GetFiles("InputPDFs", "*.pdf");
foreach (string file in files)
{
    PdfDocument doc = new PdfDocument();
    doc.LoadFromFile(file);
    for (int i = 0; i < doc.Pages.Count; i++)
    {
        Image image = doc.SaveAsImage(i, PdfImageType.Bitmap);
        string fileName = Path.GetFileNameWithoutExtension(file);
        image.Save($"Output\\{fileName}-Page{i + 1}.jpg", ImageFormat.Jpeg);
    }
    doc.Dispose();
}

Troubleshooting & Best Practices

Working with PDF-to-image conversion in .NET can come with challenges. Here’s how to address them:

  1. Large PDFs consume memory
    • Use lower DPI (e.g., 150 instead of 300).
    • Process in chunks rather than loading everything at once.
  2. Images are blurry or low quality
    • Increase DPI.
    • Consider using PNG instead of JPG for sharp diagrams or text.
  3. File paths cause errors
    • Always check that the output directory exists.
    • Use Path.Combine() for cross-platform paths.
  4. Handling password-protected PDFs
    • Provide the password when loading:
doc.LoadFromFile("secure.pdf", "password123");
  1. Dispose objects
    • Always call Dispose() on PdfDocument and Image objects to release memory.

Conclusion

Converting PDF to JPG in .NET is straightforward with Spire.PDF for .NET . The library provides the SaveAsImage() method, allowing you to convert a single page or an entire document with just a few lines of code. With options for custom resolution, stream handling, and batch conversion , you can adapt the workflow to desktop apps, web services, or cloud platforms.

By following best practices like managing memory and adjusting resolution, you can ensure efficient, high-quality output that fits your project’s requirements.

If you’re exploring more advanced document processing, Spire also offers libraries for Word, Excel, and PowerPoint, enabling a complete .NET document solution.

FAQs

Q1. Can I convert PDFs to formats other than JPG?

Yes. Spire.PDF supports PNG, BMP, SVG, and other common formats.

Q2. What DPI should I use?

  • 72 DPI for thumbnails.
  • 150 DPI for web previews.
  • 300 DPI for print quality.

Q3. Does Spire.PDF support encrypted PDFs?

Yes, but you need to provide the correct password when loading the file.

Q4. Can I integrate this in ASP.NET?

Yes. You can save images to memory streams and return them as HTTP responses.

Q5. Can I convert images back to PDF?

Yes. You can load JPG, PNG, or BMP files and insert them into PDF pages, effectively converting images back into a PDF.

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.

Installa con Maven

Install-Package Spire.XLS

Link Correlati

pagina di copertina della conversione da txt a excel con c#

Contenuto della Pagina:

Introduzione

Lavorare con file di testo semplice (.txt) è comune, ma quando si tratta di gestire grandi insiemi di dati, i file TXT spesso mancano di struttura e usabilità. Convertendo TXT in Excel, puoi sfruttare le funzionalità di Excel come filtri, formule, tabelle pivot e visualizzazione dei dati. In questa guida, imparerai tre metodi efficaci per convertire i file TXT in formato Excel (XLSX o CSV) — utilizzando Microsoft Excel, un convertitore online gratuito da TXT a Excel e la programmazione in Python.

Differenze tra file TXT, CSV ed Excel

Prima di iniziare la conversione, è importante comprendere le differenze tra questi formati:

  • File TXT – Memorizzano testo non strutturato o semplice, spesso separato da spazi, tabulazioni o delimitatori personalizzati.
  • File CSV – Una forma strutturata di file di testo in cui i dati sono separati da virgole, rendendoli più facili da importare in fogli di calcolo o database.
  • File Excel (XLS/XLSX) – Formati nativi di Microsoft Excel che supportano funzionalità avanzate di manipolazione dei dati, tra cui formule, grafici e fogli di lavoro multipli.

La conversione da TXT a Excel consente di trasformare i dati di testo grezzi in un formato strutturato e interattivo.

Metodo 1. Importare testo in Microsoft Excel e salvare in formato Excel

Per gli utenti che preferiscono non fare affidamento su strumenti esterni, Excel stesso fornisce un metodo affidabile per convertire i file TXT in fogli di calcolo strutturati. Con questo metodo, non è necessario scaricare altre API o software. Finché hai accesso a Microsoft Excel, puoi gestire la conversione in pochi secondi.

Segui i passaggi seguenti per iniziare:

Passaggio 1. Apri Microsoft Excel e vai su File > Apri > Sfoglia per aprire il tuo file TXT.

aprire file txt con microsoft excel

Passaggio 2. Apparirà una finestra per selezionare il file. Il formato file predefinito contiene solo file Excel, quindi dovresti regolare il formato del file dall'angolo in basso a destra su "Tutti i file" o "File di testo".

regolare il formato del file per aprire il file txt di destinazione sul computer

Passaggio 3. Apparirà l'Importazione guidata testo. Scegli il tipo di file (Delimitato o a larghezza fissa).

scegliere il tipo di file delimitato o a larghezza fissa

Seleziona il delimitatore corretto (come tabulazione, spazio o virgola).

regolare il delimitatore corretto come tabulazione, spazio e virgola

Regola i formati dei dati delle colonne se necessario, quindi fai clic su Fine.

regolare i formati dei dati delle colonne per terminare l'impostazione della conversione

Passaggio 4. Salva il file come .xlsx o .csv.

salvare il file in formato xlsx o csv

Metodo 2. Convertire TXT in formato Excel con C#

Per sviluppatori o utenti avanzati che gestiscono grandi quantità di dati, il codice fornisce un modo affidabile per automatizzare la conversione da TXT a Excel. Permettimi di presentarti Spire.XLS for .NET, una libreria Excel professionale progettata per consentire agli sviluppatori di creare, leggere, modificare, convertire e stampare file Excel all'interno di applicazioni .NET senza dipendere da Microsoft Excel.

Spire.XLS for .NET supporta sia i formati XLS che XLSX, insieme a CSV, ODS, PDF, HTML e altri tipi di file, rendendolo una soluzione flessibile per la gestione dei dati dei fogli di calcolo. Con il suo ricco set di funzionalità, tra cui il calcolo di formule, la creazione di grafici, le tabelle pivot, l'importazione/esportazione di dati e la formattazione avanzata, aiuta gli sviluppatori ad automatizzare in modo efficiente le attività relative a Excel, garantendo al contempo alte prestazioni e facilità di integrazione.

Ora, segui i passaggi seguenti per convertire i tuoi file TXT in formato Excel con Spire.XLS for .NET:

Passaggio 1. Installa la DLL di Spire.XLS sul tuo computer con NuGet utilizzando il codice seguente o scaricala dal sito Web ufficiale.

Passaggio 2. Copia il codice seguente e non dimenticare di personalizzarlo in base alle esigenze specifiche del tuo file:

using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List<string[]> data = new List<string[]>();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet sheet = workbook.Worksheets[0];

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

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

RISULTATO: pagina dei risultati della conversione da txt a excel con spire xls

Conclusione

La conversione di file TXT in formato Excel semplifica l'analisi, l'organizzazione e la condivisione dei dati. In questo post, abbiamo esplorato tre metodi:

  • Importazione con Microsoft Excel – rapida e integrata per le conversioni manuali.
  • Scripting in Python – potente e flessibile per l'automazione e grandi insiemi di dati.

Scegli il metodo che meglio si adatta alle tue esigenze e inizia a trasformare il testo semplice in fogli di calcolo Excel strutturati e utilizzabili.

Ottieni una licenza gratuita

Per sperimentare appieno le capacità di Spire.XLS for .NET senza alcuna limitazione di valutazione, puoi richiedere una licenza di prova gratuita di 30 giorni.

Vedi anche:

Instalar com Maven

Install-Package Spire.XLS

Links Relacionados

página de rosto da conversão de txt para excel com c#

Conteúdo da Página:

Introdução

Trabalhar com arquivos de texto simples (.txt) é comum, mas quando se trata de gerenciar grandes conjuntos de dados, os arquivos TXT muitas vezes carecem de estrutura e usabilidade. Ao converter TXT para Excel, você pode aproveitar os recursos do Excel, como filtragem, fórmulas, tabelas dinâmicas e visualização de dados. Neste guia, você aprenderá três métodos eficazes para converter arquivos TXT para o formato Excel (XLSX ou CSV) — usando o Microsoft Excel, um conversor online gratuito de TXT para Excel e programação em Python.

Diferenças entre Arquivos TXT, CSV e Excel

Antes de iniciar a conversão, é importante entender as diferenças entre esses formatos:

  • Arquivos TXT – Armazenam texto não estruturado ou simples, muitas vezes separado por espaços, tabulações ou delimitadores personalizados.
  • Arquivos CSV – Uma forma estruturada de arquivo de texto onde os dados são separados por vírgulas, facilitando a importação para planilhas ou bancos de dados.
  • Arquivos Excel (XLS/XLSX) – Formatos nativos do Microsoft Excel que suportam recursos avançados de manipulação de dados, incluindo fórmulas, gráficos e várias planilhas.

Converter TXT para Excel permite transformar dados de texto bruto em um formato estruturado e interativo.

Método 1. Importar Texto para o Microsoft Excel e Salvar como Formato Excel

Para usuários que preferem não depender de ferramentas externas, o próprio Excel fornece um método confiável para converter arquivos TXT em planilhas estruturadas. Com este método, você não precisa baixar nenhuma outra API ou software. Contanto que você tenha acesso ao Microsoft Excel, poderá gerenciar a conversão em segundos.

Siga os passos abaixo para começar:

Passo 1. Abra o Microsoft Excel e vá para Arquivo > Abrir > Procurar para abrir seu arquivo TXT.

abrir arquivo txt com o microsoft excel

Passo 2. Uma janela será exibida para você selecionar o arquivo. O formato de arquivo padrão contém apenas arquivos do Excel, então você deve ajustar o formato do arquivo no canto inferior direito para "Todos os Arquivos" ou "Arquivos de Texto".

ajustar o formato do arquivo para abrir o arquivo txt de destino no computador

Passo 3. O Assistente de Importação de Texto aparecerá. Escolha o tipo de arquivo (Delimitado ou Largura fixa).

escolher o tipo de arquivo delimitado ou de largura fixa

Selecione o delimitador correto (como tabulação, espaço ou vírgula).

ajustar o delimitador correto como tabulação, espaço e vírgula

Ajuste os formatos de dados da coluna, se necessário, e clique em Concluir.

ajustar os formatos de dados da coluna para finalizar a configuração da conversão

Passo 4. Salve o arquivo como .xlsx ou .csv.

salvar o arquivo no formato xlsx ou csv

Método 2. Converter TXT para o Formato Excel com C#

Para desenvolvedores ou usuários avançados que lidam com grandes quantidades de dados, o código fornece uma maneira confiável de automatizar a conversão de TXT para Excel. Deixe-me apresentar o Spire.XLS for .NET, uma biblioteca profissional de Excel projetada para desenvolvedores criarem, lerem, editarem, converterem e imprimirem arquivos Excel em aplicativos .NET sem depender do Microsoft Excel.

O Spire.XLS for .NET suporta os formatos XLS e XLSX, juntamente com CSV, ODS, PDF, HTML e outros tipos de arquivo, tornando-o uma solução flexível para lidar com dados de planilhas. Com seu rico conjunto de recursos — incluindo cálculo de fórmulas, criação de gráficos, tabelas dinâmicas, importação/exportação de dados e formatação avançada. Ele ajuda os desenvolvedores a automatizar tarefas relacionadas ao Excel de forma eficiente, garantindo alto desempenho e facilidade de integração.

Agora, siga os passos abaixo para converter seus arquivos TXT para o formato Excel com o Spire.XLS for .NET:

Passo 1. Instale a DLL do Spire.XLS no seu computador com o NuGet usando o código a seguir ou baixe do site oficial.

Passo 2. Copie o código a seguir e não se esqueça de personalizá-lo de acordo com as necessidades específicas do seu arquivo:

using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List<string[]> data = new List<string[]>();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet sheet = workbook.Worksheets[0];

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

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

RESULTADO: página de resultado da conversão de txt para excel com spire xls

Conclusão

A conversão de arquivos TXT para o formato Excel facilita a análise, organização e compartilhamento de seus dados. Nesta postagem, exploramos três métodos:

  • Importação do Microsoft Excel – rápido e integrado para conversões manuais.
  • Scripting em Python – poderoso e flexível para automação e grandes conjuntos de dados.

Escolha o método que melhor se adapta às suas necessidades e comece a transformar texto simples em planilhas do Excel estruturadas и utilizáveis.

Obtenha uma Licença Gratuita

Para experimentar plenamente as capacidades do Spire.XLS for .NET sem quaisquer limitações de avaliação, você pode solicitar uma licença de teste gratuita de 30 dias.

Veja também:

c#으로 txt를 excel로 변환하는 표지

페이지 내용:

소개

일반 텍스트 파일(.txt) 작업은 흔하지만, 대용량 데이터 세트를 관리할 때 TXT 파일은 종종 구조와 사용성이 부족합니다. TXT를 Excel로 변환하면 필터링, 수식, 피벗 테이블, 데이터 시각화와 같은 Excel의 기능을 활용할 수 있습니다. 이 가이드에서는 Microsoft Excel, 무료 온라인 TXT-Excel 변환기 및 Python 프로그래밍을 사용하여 TXT 파일을 Excel(XLSX 또는 CSV) 형식으로 변환하는 세 가지 효과적인 방법을 배웁니다.

TXT, CSV 및 Excel 파일 간의 차이점

변환을 시작하기 전에 이러한 형식 간의 차이점을 이해하는 것이 중요합니다.

  • TXT 파일 – 구조화되지 않은 일반 텍스트를 저장하며, 종종 공백, 탭 또는 사용자 지정 구분 기호로 구분됩니다.
  • CSV 파일 – 데이터가 쉼표로 구분된 구조화된 텍스트 파일 형식으로, 스프레드시트나 데이터베이스로 쉽게 가져올 수 있습니다.
  • Excel 파일(XLS/XLSX) – 수식, 차트, 여러 워크시트 등 고급 데이터 조작 기능을 지원하는 Microsoft Excel의 기본 형식입니다.

TXT를 Excel로 변환하면 원시 텍스트 데이터를 구조화되고 상호 작용이 가능한 형식으로 변환할 수 있습니다.

방법 1. Microsoft Excel로 텍스트를 가져와 Excel 형식으로 저장

외부 도구에 의존하고 싶지 않은 사용자를 위해 Excel 자체에서 TXT 파일을 구조화된 스프레드시트로 변환하는 신뢰할 수 있는 방법을 제공합니다. 이 방법을 사용하면 다른 API나 소프트웨어를 다운로드할 필요가 없습니다. Microsoft Excel에 액세스할 수 있는 한 몇 초 안에 변환을 관리할 수 있습니다.

시작하려면 아래 단계를 따르십시오:

1단계. Microsoft Excel을 열고 파일 > 열기 > 찾아보기를 통해 TXT 파일을 엽니다.

microsoft excel로 txt 파일 열기

2단계. 파일을 선택할 수 있는 창이 나타납니다. 기본 파일 형식은 Excel 파일만 포함하므로 오른쪽 하단 모서리에서 파일 형식을 "모든 파일" 또는 "텍스트 파일"로 조정해야 합니다.

컴퓨터에서 대상 txt 파일을 열기 위해 파일 형식 조정

3단계. 텍스트 가져오기 마법사가 나타납니다. 파일 유형(구분 기호 또는 고정 너비)을 선택합니다.

구분 기호 또는 고정 너비의 파일 유형 선택

올바른 구분 기호(예: 탭, 공백 또는 쉼표)를 선택합니다.

탭, 공백, 쉼표와 같은 올바른 구분 기호 조정

필요한 경우 열 데이터 형식을 조정한 다음 마침을 클릭합니다.

변환 설정을 완료하기 위해 열 데이터 형식 조정

4단계. 파일을 .xlsx 또는 .csv로 저장합니다.

파일을 xlsx 또는 csv 형식으로 저장

방법 2. C#을 사용하여 TXT를 Excel 형식으로 변환

대용량 데이터를 처리하는 개발자나 고급 사용자에게 코드는 TXT를 Excel로 변환하는 작업을 자동화하는 신뢰할 수 있는 방법을 제공합니다. Microsoft Excel에 의존하지 않고 .NET 애플리케이션 내에서 Excel 파일을 생성, 읽기, 편집, 변환 및 인쇄할 수 있도록 개발자를 위해 설계된 전문 Excel 라이브러리인 Spire.XLS for .NET을 소개합니다.

Spire.XLS for .NET은 XLS 및 XLSX 형식과 함께 CSV, ODS, PDF, HTML 및 기타 파일 유형을 지원하여 스프레드시트 데이터를 처리하기 위한 유연한 솔루션을 제공합니다. 수식 계산, 차트 생성, 피벗 테이블, 데이터 가져오기/내보내기 및 고급 서식 지정과 같은 풍부한 기능 세트를 통해 개발자가 Excel 관련 작업을 효율적으로 자동화하면서 높은 성능과 통합 용이성을 보장합니다.

이제 Spire.XLS for .NET을 사용하여 TXT 파일을 Excel 형식으로 변환하려면 아래 단계를 따르십시오:

1단계. 다음 코드를 사용하여 NuGet으로 컴퓨터에 Spire.XLS DLL을 설치하거나 공식 웹사이트에서 다운로드합니다.

2단계. 다음 코드를 복사하고 특정 파일 요구 사항에 맞게 사용자 지정하는 것을 잊지 마십시오:

using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List<string[]> data = new List<string[]>();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet sheet = workbook.Worksheets[0];

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

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

결과: spire xls로 txt를 excel로 변환한 결과 페이지

결론

TXT 파일을 Excel 형식으로 변환하면 데이터를 더 쉽게 분석, 구성 및 공유할 수 있습니다. 이 게시물에서는 세 가지 방법을 살펴보았습니다:

  • Microsoft Excel 가져오기 – 수동 변환을 위한 빠르고 내장된 기능.
  • Python 스크립팅 – 자동화 및 대용량 데이터 세트를 위한 강력하고 유연한 기능.

자신의 필요에 가장 적합한 방법을 선택하고 일반 텍스트를 구조화되고 사용 가능한 Excel 스프레드시트로 변환하기 시작하십시오.

무료 라이선스 받기

평가 제한 없이 Spire.XLS for .NET의 기능을 완전히 경험하려면 무료 30일 평가판 라이선스를 요청할 수 있습니다.

참조:

Installer avec Maven

Install-Package Spire.XLS

Liens connexes

page de couverture de la conversion de txt en excel avec c#

Contenu de la page :

Introduction

Travailler avec des fichiers texte brut (.txt) est courant, mais lorsqu'il s'agit de gérer de grands ensembles de données, les fichiers TXT manquent souvent de structure et de convivialité. En convertissant des fichiers TXT en Excel, vous pouvez profiter des fonctionnalités d'Excel telles que le filtrage, les formules, les tableaux croisés dynamiques et la visualisation des données. Dans ce guide, vous apprendrez trois méthodes efficaces pour convertir des fichiers TXT au format Excel (XLSX ou CSV) — en utilisant Microsoft Excel, un convertisseur TXT vers Excel en ligne gratuit, et la programmation en Python.

Différences entre les fichiers TXT, CSV et Excel

Avant de commencer la conversion, il est important de comprendre les différences entre ces formats :

  • Fichiers TXT – Stockent du texte non structuré ou brut, souvent séparé par des espaces, des tabulations ou des délimiteurs personnalisés.
  • Fichiers CSV – Une forme structurée de fichier texte où les données sont séparées par des virgules, ce qui facilite leur importation dans des tableurs ou des bases de données.
  • Fichiers Excel (XLS/XLSX) – Formats natifs de Microsoft Excel qui prennent en charge des fonctionnalités avancées de manipulation de données, y compris les formules, les graphiques et les feuilles de calcul multiples.

La conversion de TXT en Excel vous permet de transformer des données textuelles brutes en un format structuré et interactif.

Méthode 1. Importer du texte dans Microsoft Excel et enregistrer au format Excel

Pour les utilisateurs qui préfèrent ne pas dépendre d'outils externes, Excel lui-même fournit une méthode fiable pour convertir les fichiers TXT en feuilles de calcul structurées. Avec cette méthode, vous n'avez pas besoin de télécharger d'autres API ou logiciels. Tant que vous avez accès à Microsoft Excel, vous pouvez gérer la conversion en quelques secondes.

Suivez les étapes ci-dessous pour commencer :

Étape 1. Ouvrez Microsoft Excel et allez dans Fichier > Ouvrir > Parcourir pour ouvrir votre fichier TXT.

ouvrir un fichier txt avec microsoft excel

Étape 2. Une fenêtre apparaîtra pour vous permettre de sélectionner un fichier. Le format de fichier par défaut ne contient que des fichiers Excel, vous devez donc ajuster le format de fichier dans le coin inférieur droit sur « Tous les fichiers » ou « Fichiers texte ».

ajuster le format de fichier pour ouvrir le fichier txt cible sur l'ordinateur

Étape 3. L'Assistant d'importation de texte apparaîtra. Choisissez le type de fichier (Délimité ou Largeur fixe).

choisir le type de fichier délimité ou à largeur fixe

Sélectionnez le délimiteur correct (comme tabulation, espace ou virgule).

ajuster le délimiteur correct comme la tabulation, l'espace et la virgule

Ajustez les formats de données des colonnes si nécessaire, puis cliquez sur Terminer.

ajuster les formats de données des colonnes pour terminer le paramétrage de la conversion

Étape 4. Enregistrez le fichier en tant que .xlsx ou .csv.

enregistrer le fichier au format xlsx ou csv

Méthode 2. Convertir un fichier TXT au format Excel avec C#

Pour les développeurs ou les utilisateurs avancés qui manipulent de grandes quantités de données, le code offre un moyen fiable d'automatiser la conversion de TXT en Excel. Laissez-moi vous présenter Spire.XLS for .NET, une bibliothèque Excel professionnelle conçue pour les développeurs afin de créer, lire, modifier, convertir et imprimer des fichiers Excel dans des applications .NET sans dépendre de Microsoft Excel.

Spire.XLS for .NET prend en charge les formats XLS et XLSX ainsi que CSV, ODS, PDF, HTML et d'autres types de fichiers, ce qui en fait une solution flexible pour la gestion des données de feuilles de calcul. Avec son riche ensemble de fonctionnalités — y compris le calcul de formules, la création de graphiques, les tableaux croisés dynamiques, l'importation/exportation de données et la mise en forme avancée. Il aide les développeurs à automatiser efficacement les tâches liées à Excel tout en garantissant des performances élevées et une facilité d'intégration.

Maintenant, suivez les étapes ci-dessous pour convertir vos fichiers TXT au format Excel avec Spire.XLS for .NET :

Étape 1. Installez la DLL Spire.XLS sur votre ordinateur avec NuGet en utilisant le code suivant ou téléchargez-la depuis le site officiel.

Étape 2. Copiez le code suivant et n'oubliez pas de le personnaliser en fonction des besoins spécifiques de votre fichier :

using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List<string[]> data = new List<string[]>();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet sheet = workbook.Worksheets[0];

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

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

RÉSULTAT : page de résultat de la conversion de txt en excel avec spire xls

Conclusion

La conversion de fichiers TXT au format Excel facilite l'analyse, l'organisation et le partage de vos données. Dans cet article, nous avons exploré trois méthodes :

  • Importation via Microsoft Excel – rapide et intégrée pour les conversions manuelles.
  • Scripting en Python – puissant et flexible pour l'automatisation et les grands ensembles de données.

Choisissez la méthode qui correspond le mieux à vos besoins et commencez à transformer du texte brut en feuilles de calcul Excel structurées et utilisables.

Obtenir une licence gratuite

Pour profiter pleinement des capacités de Spire.XLS for .NET sans aucune limitation d'évaluation, vous pouvez demander une licence d'essai gratuite de 30 jours.

Voir aussi :

Instalar con Maven

Install-Package Spire.XLS

Enlaces Relacionados

portada de la conversión de txt a excel con c#

Contenido de la Página:

Introducción

Trabajar con archivos de texto sin formato (.txt) es común, pero cuando se trata de gestionar grandes conjuntos de datos, los archivos TXT a menudo carecen de estructura y usabilidad. Al convertir TXT a Excel, puede aprovechar las características de Excel como el filtrado, las fórmulas, las tablas dinámicas y la visualización de datos. En esta guía, aprenderá tres métodos efectivos para convertir archivos TXT a formato Excel (XLSX o CSV), utilizando Microsoft Excel, un convertidor gratuito de TXT a Excel en línea y programación en Python.

Diferencias entre archivos TXT, CSV y Excel

Antes de comenzar la conversión, es importante comprender las diferencias entre estos formatos:

  • Archivos TXT – Almacenan texto sin formato o no estructurado, a menudo separado por espacios, tabulaciones o delimitadores personalizados.
  • Archivos CSV – Una forma estructurada de archivo de texto donde los datos están separados por comas, lo que facilita su importación a hojas de cálculo o bases de datos.
  • Archivos de Excel (XLS/XLSX) – Formatos nativos de Microsoft Excel que admiten funciones avanzadas de manipulación de datos, incluidas fórmulas, gráficos y múltiples hojas de trabajo.

Convertir TXT a Excel le permite transformar datos de texto sin formato en un formato estructurado e interactivo.

Método 1. Importar texto a Microsoft Excel y guardar en formato Excel

Para los usuarios que prefieren не depender de herramientas externas, Excel mismo proporciona un método confiable para convertir archivos TXT en hojas de cálculo estructuradas. Con este método, no necesita descargar ninguna otra API o software. Siempre que tenga acceso a Microsoft Excel, puede gestionar la conversión en segundos.

Siga los pasos a continuación para comenzar:

Paso 1. Abra Microsoft Excel y vaya a Archivo > Abrir > Examinar para abrir su archivo TXT.

abrir archivo txt con microsoft excel

Paso 2. Aparecerá una ventana para que seleccione el archivo. El formato de archivo predeterminado contiene solo archivos de Excel, por lo que debe ajustar el formato de archivo desde la esquina inferior derecha a "Todos los archivos" o "Archivos de texto".

ajustar el formato del archivo para abrir el archivo txt de destino en el ordenador

Paso 3. Aparecerá el Asistente para importar texto. Elija el tipo de archivo (Delimitado o de Ancho fijo).

elegir tipo de archivo delimitado o de ancho fijo

Seleccione el delimitador correcto (como tabulación, espacio o coma).

ajustar el delimitador correcto como tabulación, espacio y coma

Ajuste los formatos de datos de las columnas si es necesario, luego haga clic en Finalizar.

ajustar los formatos de datos de las columnas para finalizar la configuración de la conversión

Paso 4. Guarde el archivo como .xlsx o .csv.

guardar el archivo en formato xlsx o csv

Método 2. Convertir TXT a formato Excel con C#

Para los desarrolladores o usuarios avanzados que manejan grandes cantidades de datos, el código proporciona una forma confiable de automatizar la conversión de TXT a Excel. Permítame presentarle Spire.XLS for .NET, una biblioteca profesional de Excel diseñada para que los desarrolladores creen, lean, editen, conviertan e impriman archivos de Excel dentro de aplicaciones .NET sin depender de Microsoft Excel.

Spire.XLS for .NET admite tanto los formatos XLS como XLSX, junto con CSV, ODS, PDF, HTML y otros tipos de archivos, lo que lo convierte en una solución flexible para manejar datos de hojas de cálculo. Con su amplio conjunto de características, que incluye cálculo de fórmulas, creación de gráficos, tablas dinámicas, importación/exportación de datos y formato avanzado. Ayuda a los desarrolladores a automatizar tareas relacionadas con Excel de manera eficiente, garantizando un alto rendimiento y facilidad de integración.

Ahora, siga los pasos a continuación para convertir sus archivos TXT a formato Excel con Spire.XLS for .NET:

Paso 1. Instale la DLL de Spire.XLS en su computadora con NuGet usando el siguiente código o descárguela desde el sitio web oficial.

Paso 2. Copie el siguiente código y no olvide personalizarlo según las necesidades específicas de su archivo:

using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List<string[]> data = new List<string[]>();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet sheet = workbook.Worksheets[0];

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

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

RESULTADO: página de resultados de la conversión de txt a excel con spire xls

Conclusión

Convertir archivos TXT a formato Excel facilita el análisis, la organización y el intercambio de sus datos. En esta publicación, exploramos tres métodos:

  • Importación de Microsoft Excel – rápido e integrado para conversiones manuales.
  • Scripting en Python – potente y flexible para la automatización y grandes conjuntos de datos.

Elija el método que mejor se adapte a sus necesidades y comience a convertir texto sin formato en hojas de cálculo de Excel estructuradas y utilizables.

Obtenga una licencia gratuita

Para experimentar plenamente las capacidades de Spire.XLS for .NET sin ninguna limitación de evaluación, puede solicitar una licencia de prueba gratuita de 30 días.

Ver también:

Mit Maven installieren

Install-Package Spire.XLS

Verwandte Links

Titelseite der Konvertierung von txt in excel mit c#

Seiteninhalt:

Einführung

Das Arbeiten mit reinen Textdateien (.txt) ist üblich, aber wenn es um die Verwaltung großer Datensätze geht, fehlt es TXT-Dateien oft an Struktur und Benutzerfreundlichkeit. Durch die Konvertierung von TXT in Excel können Sie die Funktionen von Excel wie Filtern, Formeln, Pivot-Tabellen und Datenvisualisierung nutzen. In diesem Leitfaden lernen Sie drei effektive Methoden kennen, um TXT-Dateien in das Excel-Format (XLSX oder CSV) zu konvertieren – mit Microsoft Excel, einem kostenlosen Online-TXT-zu-Excel-Konverter und Python-Programmierung.

Unterschiede zwischen TXT-, CSV- und Excel-Dateien

Bevor Sie mit der Konvertierung beginnen, ist es wichtig, die Unterschiede zwischen diesen Formaten zu verstehen:

  • TXT-Dateien – Speichern unstrukturierter oder reiner Text, oft durch Leerzeichen, Tabulatoren oder benutzerdefinierte Trennzeichen getrennt.
  • CSV-Dateien – Eine strukturierte Form einer Textdatei, bei der Daten durch Kommas getrennt sind, was den Import in Tabellenkalkulationen oder Datenbanken erleichtert.
  • Excel-Dateien (XLS/XLSX) – Native Microsoft Excel-Formate, die erweiterte Datenmanipulationsfunktionen wie Formeln, Diagramme und mehrere Arbeitsblätter unterstützen.

Die Konvertierung von TXT in Excel ermöglicht es Ihnen, Roh-Textdaten in ein strukturiertes und interaktives Format umzuwandeln.

Methode 1. Text in Microsoft Excel importieren und als Excel-Format speichern

Für Benutzer, die lieber nicht auf externe Tools angewiesen sind, bietet Excel selbst eine zuverlässige Methode, um TXT-Dateien in strukturierte Tabellenkalkulationen zu konvertieren. Mit dieser Methode müssen Sie keine anderen APIs oder Software herunterladen. Solange Sie Zugriff auf Microsoft Excel haben, können Sie die Konvertierung in Sekunden durchführen.

Befolgen Sie die folgenden Schritte, um zu beginnen:

Schritt 1. Öffnen Sie Microsoft Excel und gehen Sie zu Datei > Öffnen > Durchsuchen, um Ihre TXT-Datei zu öffnen.

txt-datei mit microsoft excel öffnen

Schritt 2. Ein Fenster wird geöffnet, in dem Sie eine Datei auswählen können. Das Standard-Dateiformat enthält nur Excel-Dateien, daher sollten Sie das Dateiformat in der rechten unteren Ecke auf „Alle Dateien“ oder „Textdateien“ ändern.

dateiformat anpassen, um die ziel-txt-datei auf dem computer zu öffnen

Schritt 3. Der Textimport-Assistent wird angezeigt. Wählen Sie den Dateityp (Getrennt oder Feste Breite).

dateityp getrennt oder feste breite wählen

Wählen Sie das richtige Trennzeichen (wie Tabulator, Leerzeichen oder Komma).

richtiges trennzeichen wie tabulator, leerzeichen und komma anpassen

Passen Sie bei Bedarf die Spaltendatenformate an und klicken Sie dann auf Fertig stellen.

spaltendatenformate anpassen, um die konvertierungseinstellung abzuschließen

Schritt 4. Speichern Sie die Datei als .xlsx oder .csv.

datei im xlsx- oder csv-format speichern

Methode 2. TXT mit C# in das Excel-Format konvertieren

Für Entwickler oder fortgeschrittene Benutzer, die große Datenmengen verarbeiten, bietet Code eine zuverlässige Möglichkeit, die Konvertierung von TXT in Excel zu automatisieren. Lassen Sie mich Ihnen Spire.XLS for .NET vorstellen, eine professionelle Excel-Bibliothek, die für Entwickler entwickelt wurde, um Excel-Dateien zu erstellen, zu lesen, zu bearbeiten, zu konvertieren und Excel-Dateien zu drucken, ohne auf Microsoft Excel angewiesen zu sein.

Spire.XLS for .NET unterstützt sowohl XLS- als auch XLSX-Formate sowie CSV, ODS, PDF, HTML und andere Dateitypen und ist somit eine flexible Lösung für die Verarbeitung von Tabellenkalkulationsdaten. Mit seinem reichhaltigen Funktionsumfang – einschließlich Formelberechnung, Diagrammerstellung, Pivot-Tabellen, Datenimport/-export und erweiterter Formatierung. Es hilft Entwicklern, Excel-bezogene Aufgaben effizient zu automatisieren und gewährleistet gleichzeitig hohe Leistung und einfache Integration.

Befolgen Sie nun die folgenden Schritte, um Ihre TXT-Dateien mit Spire.XLS for .NET in das Excel-Format zu konvertieren:

Schritt 1. Installieren Sie die Spire.XLS-DLL auf Ihrem Computer mit NuGet unter Verwendung des folgenden Codes oder laden Sie sie von der offiziellen Website herunter.

Schritt 2. Kopieren Sie den folgenden Code und vergessen Sie nicht, ihn an Ihre spezifischen Dateianforderungen anzupassen:

using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List<string[]> data = new List<string[]>();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet sheet = workbook.Worksheets[0];

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

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

ERGEBNIS: ergebnisseite der konvertierung von txt in excel mit spire xls

Fazit

Die Konvertierung von TXT-Dateien in das Excel-Format erleichtert die Analyse, Organisation und Weitergabe Ihrer Daten. In diesem Beitrag haben wir drei Methoden untersucht:

  • Microsoft Excel-Import – schnell und integriert für manuelle Konvertierungen.
  • Python-Skripting – leistungsstark und flexibel für die Automatisierung und große Datensätze.

Wählen Sie die Methode, die Ihren Bedürfnissen am besten entspricht, und beginnen Sie, reinen Text in strukturierte, nutzbare Excel-Tabellen umzuwandeln.

Holen Sie sich eine kostenlose Lizenz

Um die Funktionen von Spire.XLS for .NET ohne Evaluierungseinschränkungen vollständig zu erleben, können Sie eine kostenlose 30-Tage-Testlizenz anfordern.

Siehe auch:

Установить с помощью Maven

Install-Package Spire.XLS

Похожие ссылки

обложка преобразования txt в excel с помощью c#

Содержание страницы:

Введение

Работа с обычными текстовыми файлами (.txt) является обычным делом, но когда речь заходит об управлении большими наборами данных, TXT-файлам часто не хватает структуры и удобства использования. Преобразуя TXT в Excel, вы можете воспользоваться такими функциями Excel, как фильтрация, формулы, сводные таблицы и визуализация данных. В этом руководстве вы узнаете о трех эффективных методах преобразования TXT-файлов в формат Excel (XLSX или CSV) — с помощью Microsoft Excel, бесплатного онлайн-конвертера TXT в Excel и программирования на Python.

Различия между файлами TXT, CSV и Excel

Прежде чем начать преобразование, важно понять различия между этими форматами:

  • Файлы TXT – хранят неструктурированный или обычный текст, часто разделенный пробелами, табуляциями или пользовательскими разделителями.
  • Файлы CSV – структурированная форма текстового файла, где данные разделены запятыми, что облегчает их импорт в электронные таблицы или базы данных.
  • Файлы Excel (XLS/XLSX) – нативные форматы Microsoft Excel, которые поддерживают расширенные функции обработки данных, включая формулы, диаграммы и несколько листов.

Преобразование TXT в Excel позволяет превратить необработанные текстовые данные в структурированный и интерактивный формат.

Метод 1. Импорт текста в Microsoft Excel и сохранение в формате Excel

Для пользователей, которые предпочитают не полагаться на внешние инструменты, сам Excel предоставляет надежный метод преобразования TXT-файлов в структурированные электронные таблицы. С этим методом вам не нужно загружать какие-либо другие API или программное обеспечение. Пока у вас есть доступ к Microsoft Excel, вы можете выполнить преобразование за считанные секунды.

Следуйте приведенным ниже шагам, чтобы начать:

Шаг 1. Откройте Microsoft Excel и перейдите в Файл > Открыть > Обзор, чтобы открыть ваш TXT-файл.

открыть txt-файл в microsoft excel

Шаг 2. Появится окно для выбора файла. По умолчанию формат файла содержит только файлы Excel, поэтому вам следует изменить формат файла в правом нижнем углу на «Все файлы» или «Текстовые файлы».

изменить формат файла, чтобы открыть целевой txt-файл на компьютере

Шаг 3. Появится Мастер импорта текста. Выберите тип файла (С разделителями или Фиксированной ширины).

выбрать тип файла с разделителями или фиксированной ширины

Выберите правильный разделитель (например, табуляция, пробел или запятая).

настроить правильный разделитель, такой как табуляция, пробел и запятая

При необходимости настройте форматы данных столбцов, затем нажмите Готово.

настроить форматы данных столбцов для завершения настройки преобразования

Шаг 4. Сохраните файл как .xlsx или .csv.

сохранить файл в формате xlsx или csv

Метод 2. Преобразование TXT в формат Excel с помощью C#

Для разработчиков или продвинутых пользователей, работающих с большими объемами данных, код предоставляет надежный способ автоматизации преобразования TXT в Excel. Позвольте мне представить вам Spire.XLS for .NET, профессиональную библиотеку Excel, разработанную для создания, чтения, редактирования, преобразования и печати файлов Excel в .NET-приложениях без зависимости от Microsoft Excel.

Spire.XLS for .NET поддерживает форматы XLS и XLSX, а также CSV, ODS, PDF, HTML и другие типы файлов, что делает его гибким решением для обработки данных электронных таблиц. С его богатым набором функций, включая вычисление формул, создание диаграмм, сводные таблицы, импорт/экспорт данных и расширенное форматирование, он помогает разработчикам эффективно автоматизировать задачи, связанные с Excel, обеспечивая высокую производительность и простоту интеграции.

Теперь следуйте приведенным ниже шагам, чтобы преобразовать ваши TXT-файлы в формат Excel с помощью Spire.XLS for .NET:

Шаг 1. Установите DLL Spire.XLS на свой компьютер с помощью NuGet, используя следующий код, или загрузите с официального сайта.

Шаг 2. Скопируйте следующий код и не забудьте настроить его в соответствии с вашими конкретными потребностями файла:

using Spire.Xls;
using System.IO;
using System.Collections.Generic;

class TxtToExcelConverter
{
    static void Main()
    {
        // Open a text file and read all lines in it
        string[] lines = File.ReadAllLines("Data.txt");

        // Create a list to store the data in text file
        List<string[]> data = new List<string[]>();

        // Split data into rows and columns and add to the list
        foreach (string line in lines)
        {
            data.Add(line.Trim().Split('\t')); // Adjust delimiter as needed
        }

        // Create a Workbook object
        Workbook workbook = new Workbook();

        // Get the first worksheet
        Worksheet sheet = workbook.Worksheets[0];

        // Iterate through the rows and columns in the data list
        for (int row = 0; row < data.Count; row++)
        {
            for (int col = 0; col < data[row].Length; col++)
            {
                // Write the text data in specified cells
                sheet.Range[row + 1, col + 1].Value = data[row][col];

                // Set the header row to Bold
                sheet.Range[1, col + 1].Style.Font.IsBold = true;
            }
        }

        // Autofit columns
        sheet.AllocatedRange.AutoFitColumns();

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

РЕЗУЛЬТАТ: страница результатов преобразования txt в excel с помощью spire xls

Заключение

Преобразование TXT-файлов в формат Excel облегчает анализ, организацию и обмен данными. В этом посте мы рассмотрели три метода:

  • Импорт в Microsoft Excel – быстрый и встроенный способ для ручных преобразований.
  • Скрипты на Python – мощный и гибкий инструмент для автоматизации и работы с большими наборами данных.

Выберите метод, который наилучшим образом соответствует вашим потребностям, и начните превращать обычный текст в структурированные и удобные для использования электронные таблицы Excel.

Получить бесплатную лицензию

Чтобы в полной мере оценить возможности Spire.XLS for .NET без каких-либо ограничений, вы можете запросить бесплатную 30-дневную пробную лицензию.

Смотрите также:

Python Guide to Export HTML to Markdown

Converting HTML to Markdown using Python is a common task for developers managing web content, documentation, or API data. While HTML provides powerful formatting and structure, it can be verbose and harder to maintain for tasks like technical writing or static site generation. Markdown, by contrast, is lightweight, human-readable, and compatible with platforms such as GitHub, GitLab, Jekyll, and Hugo.

Automating HTML to Markdown conversion with Python streamlines workflows, reduces errors, and ensures consistent output. This guide covers everything from converting HTML files and strings to batch processing multiple files, along with best practices to ensure accurate Markdown results.

What You Will Learn

Why Convert HTML to Markdown?

Before diving into the code, let’s look at why developers often prefer Markdown over raw HTML in many workflows:

  • Simplicity and Readability
    Markdown is easier to read and edit than verbose HTML tags.
  • Portability Across Tools
    Markdown is supported by GitHub, GitLab, Bitbucket, Obsidian, Notion, and static site generators like Hugo and Jekyll.
  • Better for Version Control
    Being plain text, Markdown makes it easier to track changes with Git, review diffs, and collaborate.
  • Faster Content Creation
    Writing Markdown is quicker than remembering HTML tag structures.
  • Integration with Static Site Generators
    Popular frameworks rely on Markdown as the main content format. Converting from HTML ensures smooth migration.
  • Cleaner Documentation Workflows
    Many documentation systems and wikis use Markdown as their primary format.

In short, converting HTML to Markdown improves maintainability, reduces clutter, and fits seamlessly into modern developer workflows.

Install HTML to Markdown Library for Python

Before converting HTML content to Markdown in Python, you’ll need a library that can handle both formats effectively. Spire.Doc for Python is a reliable choice that allows you to transform HTML files or HTML strings into Markdown while keeping headings, lists, images, and links intact.

You can install it from PyPI using pip:

pip install spire.doc

Once installed, you can automate the HTML to Markdown conversion in your Python scripts. The same library also supports broader scenarios. For example, when you need editable documents, you can rely on its HTML to Word conversion feature to transform web pages into Word files. And for distribution or archiving, HTML to PDF conversion is especially useful for generating standardized, platform-independent documents.

Convert an HTML File to Markdown in Python

One of the most common use cases is converting an existing .html file into a .md file. This is especially useful when migrating old websites, technical documentation, or blog posts into Markdown-based workflows, such as static site generators (Jekyll, Hugo) or Git-based documentation platforms (GitHub, GitLab, Read the Docs).

Steps

  • Create a new Document instance.
  • Load the .html file into the document using LoadFromFile().
  • Save the document as a .md file using SaveToFile() with FileFormat.Markdown.
  • Close the document to release resources.

Code Example

from spire.doc import *

# Create a Document instance
doc = Document()

# Load an existing HTML file
doc.LoadFromFile("input.html", FileFormat.Html)

# Save as Markdown file
doc.SaveToFile("output.md", FileFormat.Markdown)

# Close the document
doc.Close()

This converts input.html into output.md, preserving structural elements such as headings, paragraphs, lists, links, and images.

Python Example to Convert HTML File to Markdown

If you’re also interested in the reverse process, check out our guide on converting Markdown to HTML in Python.

Convert an HTML String to Markdown in Python

Sometimes, HTML content is not stored in a file but is dynamically generated—for example, when retrieving web content from an API or scraping. In these scenarios, you can convert directly from a string without needing to create a temporary HTML file.

Steps

  • Create a new Document instance.
  • Add a Section to the document.
  • Add a Paragraph to the section.
  • Append the HTML string to the paragraph using AppendHTML().
  • Save the document as a Markdown file using SaveToFile().
  • Close the document to release resources.

Code Example

from spire.doc import *

# Sample HTML string
html_content = """
<h1>Welcome</h1>
<p>This is a <strong>sample</strong> paragraph with <em>emphasis</em>.</p>
<ul>
  <li>First item</li>
  <li>Second item</li>
</ul>
"""

# Create a Document instance
doc = Document()

# Add a section
section = doc.AddSection()

# Add a paragraph and append the HTML string
paragraph = section.AddParagraph()
paragraph.AppendHTML(html_content)

# Save the document as Markdown
doc.SaveToFile("string_output.md", FileFormat.Markdown)

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

The resulting Markdown will look like this:

Python Example to Convert HTML String to Markdown

Batch Conversion of Multiple HTML Files

For larger projects, you may need to convert multiple .html files in bulk. A simple loop can automate the process.

import os
from spire.doc import *

# Define the folder containing HTML files to convert
input_folder = "html_files"

# Define the folder where converted Markdown files will be saved
output_folder = "markdown_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 files with .html extension
    if filename.endswith(".html"):
        # Create a new Document object
        doc = Document()

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

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

        # Save the Document as a Markdown file
        doc.SaveToFile(output_file, FileFormat.Markdown)

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

This script processes all .html files inside html_files/ and saves the Markdown results into markdown_files/.

Best Practices for HTML to Markdown Conversion

Turning HTML to Markdown makes content easier to read, manage, and version-control. To ensure accurate and clean conversion, follow these best practices:

  • Validate HTML Before Conversion
    Ensure your HTML is properly structured. Invalid tags can cause incomplete or broken Markdown output.
  • Understand Markdown Limitations
    Markdown does not support advanced CSS styling or custom HTML tags. Some formatting might get lost.
  • Choose File Encoding Carefully
    Always be aware of character encoding. Open and save your files with a specific encoding (like UTF-8) to prevent issues with special characters.
  • Batch Processing

If converting multiple files, create a robust script that includes error handling (try-except blocks), logging, and skips problematic files instead of halting the entire process.

Conclusion

Converting HTML to Markdown in Python is a valuable skill for developers handling documentation pipelines, migrating web content, or processing data from APIs. With Spire.Doc for Python, you can:

  • Convert individual HTML files into Markdown with ease.
  • Transform HTML strings directly into .md files.
  • Automate batch conversions to efficiently manage large projects.

By applying these methods, you can streamline your workflows and ensure your content remains clean, maintainable, and ready for modern publishing platforms.

FAQs

Q1: Can I convert Markdown back to HTML in Python?

A1: Yes, Spire.Doc supports the conversion of Markdown to HTML, allowing for seamless transitions between these formats.

Q2: Will the conversion preserve complex HTML elements like tables?

A2: While Spire.Doc effectively handles standard HTML elements, it's advisable to review complex layouts, such as tables and nested elements, to ensure accurate conversion results.

Q3: Can I automate batch conversion for multiple HTML files?

A3: Absolutely! You can automate batch conversion using scripts in Python, enabling efficient processing of multiple HTML files at once.

Q4: Is Spire.Doc free to use?

A4: Spire.Doc provides both free and commercial versions, giving developers the flexibility to access essential features at no cost or unlock advanced functionality with a license.

Spire.PDFViewer for MAUI is a dedicated PDF viewing component tailored for .NET Multi-platform App UI (MAUI) frameworks. This guide will show you how to configure it in your .NET MAUI project, including environment setup, product installation, and core PDF viewing feature implementation.

1. Prerequisites & Environment Setup

Ensure your development environment meets the following requirements before you begin.

1.1 Required Software

  • IDE: Visual Studio 2022 (version 17.8 or later) for Windows, or Visual Studio 2022 for Mac (version 17.6 or later).
  • Target Frameworks:
    • Android 5.0 (API 21) or higher
    • Windows 11, or Windows 10 Version 1809 or higher

1.2 Install the .NET MAUI Workload

The .NET Multi-platform App UI development workload is mandatory for MAUI projects. Follow these steps to install it:

  • Open Visual Studio Installer:
    • Search for "Visual Studio Installer" in your Start Menu (usually under the "Visual Studio 2022" folder).
    • Alternatively, open Visual Studio, go to “Tools > Get Tools and Features”.
  • Modify Your Installation:
    • Click "Modify" next to your Visual Studio 2022 edition.
    • Navigate to the "Workloads" tab.
    • Check the box for ".NET Multi-platform App UI development".
    • Ensure the optional components you need are selected.
    • Click "Modify" to start the installation

Select the .NET MAUI workload in Visual Studio Installer

2. Create a New .NET MAUI Project

After installing MAUI, follow these steps to create a new .NET MAUI project:

2.1 Select the Project Template

  • Open Visual Studio and click “Create a new project”.
  • Search for "MAUI" and select the .NET MAUI App template (C#).
  • Click “Next” to proceed.

Choose the .NET MAUI App template

2.2 Configure Project Details

  • Enter a project name (e.g., "PdfViewerMauiApp") and choose a Save location.
  • Next, select .NET 7.0 or later (e.g., .NET 8.0) as the target framework.
  • Click “Create” to generate the project.

Select the .NET framework version

3. Install Spire.PDFViewer and Dependencies

To implement the PDF viewer in .NET MAUI, you need to install the dependent NuGet packages and add Spire.PDFViewer DLLs.

3.1 Install Dependent NuGet Packages

  • Go to “Tools > NuGet Package Manager > Package Manager Console”.
  • Run the following command to install all required packages at once:
Install-Package Microsoft.Win32.Registry -Version 5.0.0
Install-Package System.Security.Permissions -Version 4.7.0
Install-Package System.Text.Encoding.CodePages -Version 4.7.0
Install-Package System.Security.Cryptography.Pkcs -Version 4.7.0
Install-Package System.Security.Cryptography.Xml -Version 4.7.1
Install-Package HarfBuzzSharp -Version 8.3.0.1
Install-Package SkiaSharp -Version 3.116.1
Install-Package SkiaSharp.Views.Maui.Controls -Version 2.88.5
Install-Package System.Buffers -Version 4.5.1
Install-Package System.Memory -Version 4.5.5

3.2 Add Spire.PDFViewer DLLs

  • Download the Spire.PdfViewer package from the official website.
  • Unzip the downloaded file to a specified file path.
  • In Visual Studio’s Solution Explorer, right-click the project > Add > Project Reference.
  • Click “Browse”, navigate to the unzipped folder (BIN\NET7.0\windows10.0.19041.0), and add both:
    • Spire.PdfViewer.Maui.dll
    • Spire.Pdf.dll

Add dependencies and Spire.PDFViewer dlls

3.3 Restrict Target Platform to Windows

Currently, the Spire.PDFViewer for MAUI only supports the Windows platform. Therefore, it’s necessary to modify the project file (.csproj) to remove non-Windows target frameworks:

  • In Solution Explorer, right-click the project and select “Edit Project File”.
  • Locate the <TargetFrameworks> element and delete or comment out this line.
  • Save the file (Ctrl+S) and reload the project when prompted by Visual Studio.

Remove non-Windows target frameworks

4. Add PDF Viewer to the Project

4.1 Initialize Spire.PDFViewer

In “MauiProgram.cs”, add the .UseSpirePdfViewer() method in the MauiAppBuilder chain:

Add Spire.PDFViewer initialization code

4.2 Option 1: Use the Default PDF Viewer UI

For a quick setup with a pre-built toolbar (supports loading, zooming, and searching), use the minimal XAML configuration:

  • Replace the default XAML content of “MainPage.xaml” with the following:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:spire="clr-namespace:Spire.PdfViewer.Maui;assembly=Spire.PdfViewer.Maui"
             x:Class="PdfViewerMauiApp.MainPage"> <!-- Modify “PdfViewerMauiApp” to match your project name -->
    
    <Grid ColumnDefinitions="Auto, *" ColumnSpacing="0">
        <!-- Default PDF Viewer with built-in toolbar -->
        <spire:PdfViewer x:Name="PdfDocumentViewer1" Grid.Column="1" />
    </Grid>
</ContentPage>
  • Open “MainPage.xaml.cs” and ensure the namespace matches your project name:
namespace PdfViewerMauiApp; // Match the project name in the x:Class value

public partial class MainPage : ContentPage
{

    public MainPage()
    {
        InitializeComponent();
    }

}

Configure the default PDF viewer

When you run the project, a PDF viewer with a built-in toolbar (Home, Zoom, Find) will appear. You can load PDFs directly via the toolbar and use its default features.

Default Spire.PDFViewer with built-in toolbar

4.3 Option 2: Customize the UI Layout & Functionality

For a tailored experience (e.g., a dedicated "Load PDF" button or page navigation), design a custom layout and implement core logic.

Step 1: Design the Custom UI (MainPage.xaml)

Replace the default XAML content of “MainPage.xaml” with a two-column grid (left: control panel; right: PDF viewer):

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:spire="clr-namespace:Spire.PdfViewer.Maui;assembly=Spire.PdfViewer.Maui"
             x:Class="PdfViewerMauiApp.MainPage"> <!-- Modify “PdfViewerMauiApp” to match your project name -->
    
    <Grid ColumnDefinitions="Auto, *" ColumnSpacing="0">
        <!-- Left Control Panel -->
        <VerticalStackLayout Grid.Column="0" WidthRequest="220"
                           Padding="10" Spacing="10">
            <!-- Button to load PDF files -->
            <Button Text="Load PDF File"
                   Clicked="LoadFromFile_Clicked"
                   HeightRequest="40"/>

            <!-- Page Navigation: Entry + Button -->
            <HorizontalStackLayout Spacing="10">
                <Entry x:Name="pageEntry"
                       WidthRequest="100"
                       HeightRequest="40"
                       Keyboard="Numeric"
                       Placeholder="Page Number"/>

                <Button Text="Go To"
                       Clicked="GoPages_Clicked"
                       WidthRequest="80"
                       HeightRequest="40"/>
            </HorizontalStackLayout>
            <Label x:Name="lbl1" HeightRequest="30"/>
        </VerticalStackLayout>

        <!-- Right PDF Viewing Area -->
        <spire:PdfDocumentViewer x:Name="PdfDocumentViewer1" Grid.Column="1" />
    </Grid>
</ContentPage>

Step 2: Add Functionality (MainPage.xaml.cs)

Add event handlers in “MainPage.xaml.cs” to enable PDF loading and page navigation:

namespace PdfViewerMauiApp; // Match your project name

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        // Click event for the Load PDF File button
        private async void LoadFromFile_Clicked(object sender, EventArgs e)
        {
            try
            {
                // Restrict file picker to PDF files only
                var result = await FilePicker.PickAsync(new PickOptions
                {
                    FileTypes = FilePickerFileType.Pdf,
                    PickerTitle = "Choose a PDF file"
                });

                if (result != null)
                {
                    // Load the PDF file from the selected path
                    PdfDocumentViewer1.LoadFromFile(result.FullPath);

                }
            }
            catch (Exception ex)
            {
                // Display error message
                lbl1.Text = $"Loading failed: {ex.Message}";
            }
        }

        // Click event for page navigation button
        private void GoPages_Clicked(object sender, EventArgs e)
        {
             
            if (int.TryParse(pageEntry.Text, out int pageNumber) && pageNumber > 0)
            {
                    // Verify that the page number is within the valid range.
                if (pageNumber <= PdfDocumentViewer1.PageCount)
                 {
                        // Jump to a specific page number
                     PdfDocumentViewer1.GotoPage(pageNumber, true);
                     lbl1.Text = $"Navigated to Page: {pageNumber}/{PdfDocumentViewer1.PageCount}";
                 }
                 else
                 {
                     lbl1.Text = $"Out of Range (Max Page: {PdfDocumentViewer1.PageCount})";
                 }
             }
             else
             {
                 lbl1.Text = "Please enter a valid page number.";
             }
         }
     }

Step 3: Run the Project

Run the application, and test the PDF viewer functionality:

  • Click “Load PDF File” to select and open a PDF.

  • Enter a page number and click “Go To” to navigate to that page.

Custom PDF viewer with page navigation

Integrating Spire.PDFViewer into a .NET MAUI project enables developers to quickly add robust, user-friendly PDF viewing capabilities, including document loading, page navigation, and built-in/ custom UI controls. By following the steps outlined here, developers can avoid common pitfalls (e.g., version mismatches, missing dependencies) and deploy a functional PDF viewer in minimal time.

Page 1 of 29