Monday, 18 December 2023 02:54

Python: converti HTML in Word

Mentre l'HTML è progettato per la visualizzazione online, i documenti Word vengono comunemente utilizzati per la stampa e la documentazione fisica. La conversione di HTML in Word garantisce che il contenuto sia ottimizzato per la stampa, consentendo interruzioni di pagina, intestazioni, piè di pagina e altri elementi necessari accurati per scopi di documentazione professionale. In questo articolo spiegheremo come convertire HTML in Word in Python utilizzando Spire.Doc for Python.

Installa Spire.Doc for Python

Questo scenario richiede Spire.Doc for Python e plum-dispatch v1.7.4. Possono essere facilmente installati nel tuo VS Code tramite i seguenti comandi pip.

pip install Spire.Doc

Se non sei sicuro su come installare, fai riferimento a questo tutorial: Come installare Spire.Doc for Python in VS Code

Converti un file HTML in Word con Python

Puoi convertire facilmente un file HTML in formato Word utilizzando il metodo Document.SaveToFile() fornito da Spire.Doc for Python. I passaggi dettagliati sono i seguenti.

  • Crea un oggetto della classe Document.
  • Carica un file HTML utilizzando il metodo Document.LoadFromFile().
  • Salva il file HTML in formato Word utilizzando il metodo Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the input and output file paths
inputFile = "Input.html"
outputFile = "HtmlToWord.docx"

# Create an object of the Document class
document = Document()
# Load an HTML file
document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none)

# Save the HTML file to a .docx file
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Python: Convert HTML to Word

Converti una stringa HTML in Word con Python

Per convertire una stringa HTML in Word, è possibile utilizzare il metodo Paragraph.AppendHTML(). I passaggi dettagliati sono i seguenti.

  • Crea un oggetto della classe Document.
  • Aggiungi una sezione al documento utilizzando il metodo Document.AddSection().
  • Aggiungi un paragrafo alla sezione utilizzando il metodo Sezione.AddParagraph().
  • Aggiungi una stringa HTML al paragrafo utilizzando il metodo Paragraph.AppendHTML().
  • Salvare il documento risultante utilizzando il metodo Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the output file path
outputFile = "HtmlStringToWord.docx"

# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()

# Add a paragraph to the section
paragraph = sec.AddParagraph()

# Specify the HTML string
htmlString = """
<html>
<head>
    <title>HTML to Word Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        h1 {
            color: #FF5733;
            font-size: 24px;
            margin-bottom: 20px;
        }
        p {
            color: #333333;
            font-size: 16px;
            margin-bottom: 10px;
        }
        ul {
            list-style-type: disc;
            margin-left: 20px;
            margin-bottom: 15px;
        }
        li {
            font-size: 14px;
            margin-bottom: 5px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 20px;
        }
        th, td {
            border: 1px solid #CCCCCC;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #F2F2F2;
            font-weight: bold;
        }
        td {
            color: #0000FF;
        }
    </style>
</head>
<body>
    <h1>This is a Heading</h1>
    <p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
    <p>Here's an example of an unordered list:</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <p>And here's a table:</p>
    <table>
        <tr>
            <th>Product</th>
            <th>Quantity</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>Jacket</td>
            <td>30</td>
            <td>$150</td>
        </tr>
        <tr>
            <td>Sweater</td>
            <td>25</td>
            <td>$99</td>
        </tr>
    </table>
</body>
</html>
"""

# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)

# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Python: Convert HTML to Word

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Monday, 18 December 2023 02:53

Python : convertir du HTML en Word

Alors que le HTML est conçu pour être visualisé en ligne, les documents Word sont couramment utilisés pour l'impression et la documentation physique. La conversion HTML en Word garantit que le contenu est optimisé pour l'impression, permettant des sauts de page, des en-têtes, des pieds de page et d'autres éléments nécessaires à des fins de documentation professionnelle. Dans cet article, nous expliquerons comment convertissez du HTML en Word en Python à l'aide de Spire.Doc for Python.

Installer Spire.Doc for Python

Ce scénario nécessite Spire.Doc for Python et plum-dispatch v1.7.4. Ils peuvent être facilement installés dans votre VS Code via les commandes pip suivantes.

pip install Spire.Doc

Si vous ne savez pas comment procéder à l'installation, veuillez vous référer à ce didacticiel : Comment installer Spire.Doc for Python dans VS Code

Convertir un fichier HTML en Word avec Python

Vous pouvez facilement convertir un fichier HTML au format Word en utilisant la méthode Document.SaveToFile() fournie par Spire.Doc for Python. Les étapes détaillées sont les suivantes.

  • Créez un objet de la classe Document.
  • Chargez un fichier HTML à l'aide de la méthode Document.LoadFromFile().
  • Enregistrez le fichier HTML au format Word à l'aide de la méthode Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the input and output file paths
inputFile = "Input.html"
outputFile = "HtmlToWord.docx"

# Create an object of the Document class
document = Document()
# Load an HTML file
document.LoadFromFile(inputFile, FileFormat.Html, XHTMLValidationType.none)

# Save the HTML file to a .docx file
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Python: Convert HTML to Word

Convertir une chaîne HTML en Word avec Python

Pour convertir une chaîne HTML en Word, vous pouvez utiliser la méthode Paragraph.AppendHTML(). Les étapes détaillées sont les suivantes.

  • Créez un objet de la classe Document.
  • Ajoutez une section au document à l'aide de la méthode Document.AddSection().
  • Ajoutez un paragraphe à la section à l’aide de la méthode Section.AddParagraph().
  • Ajoutez une chaîne HTML au paragraphe à l’aide de la méthode Paragraph.AppendHTML().
  • Enregistrez le document résultat à l'aide de la méthode Document.SaveToFile().
  • Python
from spire.doc import *
from spire.doc.common import *

# Specify the output file path
outputFile = "HtmlStringToWord.docx"

# Create an object of the Document class
document = Document()
# Add a section to the document
sec = document.AddSection()

# Add a paragraph to the section
paragraph = sec.AddParagraph()

# Specify the HTML string
htmlString = """
<html>
<head>
    <title>HTML to Word Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        h1 {
            color: #FF5733;
            font-size: 24px;
            margin-bottom: 20px;
        }
        p {
            color: #333333;
            font-size: 16px;
            margin-bottom: 10px;
        }
        ul {
            list-style-type: disc;
            margin-left: 20px;
            margin-bottom: 15px;
        }
        li {
            font-size: 14px;
            margin-bottom: 5px;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            margin-bottom: 20px;
        }
        th, td {
            border: 1px solid #CCCCCC;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #F2F2F2;
            font-weight: bold;
        }
        td {
            color: #0000FF;
        }
    </style>
</head>
<body>
    <h1>This is a Heading</h1>
    <p>This is a paragraph demonstrating the conversion of HTML to Word document.</p>
    <p>Here's an example of an unordered list:</p>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
    </ul>
    <p>And here's a table:</p>
    <table>
        <tr>
            <th>Product</th>
            <th>Quantity</th>
            <th>Price</th>
        </tr>
        <tr>
            <td>Jacket</td>
            <td>30</td>
            <td>$150</td>
        </tr>
        <tr>
            <td>Sweater</td>
            <td>25</td>
            <td>$99</td>
        </tr>
    </table>
</body>
</html>
"""

# Append the HTML string to the paragraph
paragraph.AppendHTML(htmlString)

# Save the result document
document.SaveToFile(outputFile, FileFormat.Docx2016)
document.Close()

Python: Convert HTML to Word

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Monday, 18 December 2023 02:49

Python: Convert Text to Word or Word to Text

Install with Pip

pip install Spire.Doc

Related Links

Text files are a common file type that contain only plain text without any formatting or styles. If you want to apply formatting or add images, charts, tables, and other media elements to text files, one of the recommended solutions is to convert them to Word files.

Conversely, if you want to efficiently extract content or reduce the file size of Word documents, you can convert them to text format. This article will demonstrate how to programmatically convert text files to Word format and convert Word files to text format using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip commands.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python in VS Code

Convert Text (TXT) to Word in Python

Conversion from TXT to Word is quite simple that requires only a few lines of code. The following are the detailed steps.

  • Create a Document object.
  • Load a text file using Document.LoadFromFile(string fileName) method.
  • Save the text file as a Word file using Document.SaveToFile(string fileName, FileFormat fileFormat) method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Convert Word to Text (TXT) in Python

The Document.SaveToFile(string fileName, FileFormat.Txt) method provided by Spire.Doc for Python allows you to export a Word file to text format. The following are the detailed steps.

  • Create a Document object.
  • Load a Word file using Document.LoadFromFile(string fileName) method.
  • Save the Word file in txt format using Document.SaveToFile(string fileName, FileFormat.Txt) method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Instalar com Pip

pip install Spire.Doc

Links Relacionados

Arquivos de texto são um tipo de arquivo comum que contém apenas texto simples, sem qualquer formatação ou estilo. Se você deseja aplicar formatação ou adicionar imagens, gráficos, tabelas e outros elementos de mídia a arquivos de texto, uma das soluções recomendadas é convertê-los em arquivos Word.

Por outro lado, se quiser extrair conteúdo com eficiência ou reduzir o tamanho do arquivo de documentos do Word, você pode convertê-los para o formato de texto. Este artigo demonstrará como programar converta arquivos de texto para o formato Word e converta arquivos do Word para o formato de texto usando Spire.Doc for Python.

Instale Spire.Doc for Python

Este cenário requer Spire.Doc for Python e plum-dispatch v1.7.4. Eles podem ser facilmente instalados em seu VS Code por meio dos seguintes comandos pip.

pip install Spire.Doc

Se você não tiver certeza de como instalar, consulte este tutorial: Como instalar Spire.Doc for Python no código VS

Converter texto (TXT) em Word em Python

A conversão de TXT para Word é bastante simples e requer apenas algumas linhas de código. A seguir estão as etapas detalhadas.

  • Crie um objeto Documento.
  • Carregue um arquivo de texto usando o método Document.LoadFromFile(string fileName).
  • Salve o arquivo de texto como um arquivo Word usando o método Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Converter Word em Texto (TXT) em Python

O método Document.SaveToFile(string fileName, FileFormat.Txt) fornecido por Spire.Doc for Python permite exportar um arquivo Word para formato de texto. A seguir estão as etapas detalhadas.

  • Crie um objeto Documento.
  • Carregue um arquivo Word usando o método Document.LoadFromFile(string fileName).
  • Salve o arquivo Word em formato txt usando o método Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Solicite uma licença temporária

Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.

Veja também

Текстовые файлы — это распространенный тип файлов, который содержит только простой текст без какого-либо форматирования или стилей. Если вы хотите применить форматирование или добавить изображения, диаграммы, таблицы и другие элементы мультимедиа в текстовые файлы, одним из рекомендуемых решений является преобразование их в файлы Word.

И наоборот, если вы хотите эффективно извлечь содержимое или уменьшить размер файлов документов Word, вы можете преобразовать их в текстовый формат. В этой статье будет показано, как программно конвертируйте текстовые файлы в формат Word и конвертируйте файлы Word в текстовый формат с помощью Spire.Doc for Python.

Установите Spire.Doc for Python

Для этого сценария требуется Spire.Doc for Python и Plum-Dispatch v1.7.4. Их можно легко установить в ваш VS Code с помощью следующих команд pip.

pip install Spire.Doc

Если вы не знаете, как установить, обратитесь к этому руководству: Как установить Spire.Doc for Python в VS Code.

Преобразование текста (TXT) в Word на Python

Преобразование из TXT в Word довольно простое и требует всего лишь нескольких строк кода. Ниже приведены подробные шаги.

  • Создайте объект Документ.
  • Загрузите текстовый файл с помощью метода Document.LoadFromFile(string fileName).
  • Сохраните текстовый файл как файл Word, используя метод Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Преобразование слова в текст (TXT) в Python

Метод Document.SaveToFile(string fileName, FileFormat.Txt), предоставляемый Spire.Doc for Python, позволяет экспортировать файл Word в текстовый формат. Ниже приведены подробные шаги.

  • Создайте объект Документ.
  • Загрузите файл Word с помощью метода Document.LoadFromFile(string fileName).
  • Сохраните файл Word в формате txt, используя метод Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Подать заявку на временную лицензию

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

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

Textdateien sind ein gängiger Dateityp, der nur einfachen Text ohne jegliche Formatierung oder Stile enthält. Wenn Sie Textdateien formatieren oder Bilder, Diagramme, Tabellen und andere Medienelemente hinzufügen möchten, besteht eine der empfohlenen Lösungen darin, sie in Word-Dateien zu konvertieren.

Wenn Sie umgekehrt Inhalte effizient extrahieren oder die Dateigröße von Word-Dokumenten reduzieren möchten, können Sie diese in das Textformat konvertieren. In diesem Artikel wird die programmgesteuerte Vorgehensweise demonstriert Konvertieren Sie Textdateien in das Word-Format und konvertieren Sie Word-Dateien in das Textformat mit Spire.Doc for Python.

Installieren Sie Spire.Doc for Python

Dieses Szenario erfordert Spire.Doc for Python und plum-dispatch v1.7.4. Sie können mit den folgenden Pip-Befehlen einfach in Ihrem VS-Code installiert werden.

pip install Spire.Doc

Wenn Sie sich bei der Installation nicht sicher sind, lesen Sie bitte dieses Tutorial: So installieren Sie Spire.Doc for Python in VS Code

Konvertieren Sie Text (TXT) in Word in Python

Die Konvertierung von TXT nach Word ist recht einfach und erfordert nur wenige Codezeilen. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Textdatei mit der Methode Document.LoadFromFile(string fileName).
  • Speichern Sie die Textdatei mit der Methode Document.SaveToFile(string fileName, FileFormat fileFormat) als Word-Datei.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Konvertieren Sie Word in Text (TXT) in Python

Mit der von Spire.Doc for Python bereitgestellten Methode Document.SaveToFile(string fileName, FileFormat.Txt) können Sie eine Word-Datei in das Textformat exportieren. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein Document-Objekt.
  • Laden Sie eine Word-Datei mit der Methode Document.LoadFromFile(string fileName).
  • Speichern Sie die Word-Datei im TXT-Format mit der Methode Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Instalar con Pip

pip install Spire.Doc

enlaces relacionados

Los archivos de texto son un tipo de archivo común que contiene solo texto sin formato sin ningún formato ni estilo. Si desea aplicar formato o agregar imágenes, gráficos, tablas y otros elementos multimedia a archivos de texto, una de las soluciones recomendadas es convertirlos a archivos de Word.

Por el contrario, si desea extraer contenido de manera eficiente o reducir el tamaño de archivo de documentos de Word, puede convertirlos a formato de texto. Este artículo demostrará cómo programar convierta archivos de texto a formato Word y convierta archivos de Word a formato de texto usando Spire.Doc for Python.

Instalar Spire.Doc for Python

Este escenario requiere Spire.Doc for Python y plum-dispatch v1.7.4. Se pueden instalar fácilmente en su código VS mediante los siguientes comandos pip.

pip install Spire.Doc

Si no está seguro de cómo instalarlo, consulte este tutorial: Cómo instalar Spire.Doc for Python en VS Code

Convertir texto (TXT) a Word en Python

La conversión de TXT a Word es bastante simple y requiere sólo unas pocas líneas de código. Los siguientes son los pasos detallados.

  • Crea un objeto de documento.
  • Cargue un archivo de texto utilizando el método Document.LoadFromFile(string fileName).
  • Guarde el archivo de texto como un archivo de Word utilizando el método Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Convertir palabra a texto (TXT) en Python

El método Document.SaveToFile(string fileName, FileFormat.Txt) proporcionado por Spire.Doc for Python le permite exportar un archivo de Word a formato de texto. Los siguientes son los pasos detallados.

  • Crea un objeto de documento.
  • Cargue un archivo de Word utilizando el método Document.LoadFromFile (nombre de archivo de cadena).
  • Guarde el archivo de Word en formato txt utilizando el método Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Solicitar una licencia temporal

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

Ver también

텍스트 파일은 서식이나 스타일 없이 일반 텍스트만 포함하는 일반적인 파일 형식입니다. 텍스트 파일에 서식을 적용하거나 이미지, 차트, 표 및 기타 미디어 요소를 추가하려는 경우 권장되는 해결 방법 중 하나는 해당 텍스트를 Word 파일로 변환하는 것입니다.

반대로 콘텐츠를 효율적으로 추출하고 싶거나 Word 문서의 파일 크기를 줄이고 싶다면 텍스트 형식으로 변환하면 됩니다. 이 문서에서는 프로그래밍 방식으로 방법을 보여줍니다 텍스트 파일을 Word 형식으로 변환 그리고 Word 파일을 텍스트 형식으로 변환 Spire.Doc for Python 사용합니다.

Spire.Doc for Python 설치

이 시나리오에는 Spire.Doc for Python 및 Plum-dispatch v1.7.4가 필요합니다. 다음 pip 명령을 통해 VS Code에 쉽게 설치할 수 있습니다.

pip install Spire.Doc

설치 방법을 잘 모르는 경우 다음 튜토리얼을 참조하세요: VS Code에서 Spire.Doc for Python 설치하는 방법

Python에서 텍스트(TXT)를 Word로 변환

TXT에서 Word로의 변환은 몇 줄의 코드만 있으면 매우 간단합니다. 자세한 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile(string fileName) 메서드를 사용하여 텍스트 파일을 로드합니다.
  • Document.SaveToFile(string fileName, FileFormat fileFormat) 메서드를 사용하여 텍스트 파일을 Word 파일로 저장합니다.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Python에서 Word를 텍스트(TXT)로 변환

Spire.Doc for Python에서 제공하는 Document.SaveToFile(string fileName, FileFormat.Txt) 메서드를 사용하면 Word 파일을 텍스트 형식으로 내보낼 수 있습니다. 자세한 단계는 다음과 같습니다.

  • 문서 개체를 만듭니다.
  • Document.LoadFromFile(string fileName) 메서드를 사용하여 Word 파일을 로드합니다.
  • Document.SaveToFile(string fileName, FileFormat.Txt) 메서드를 사용하여 Word 파일을 txt 형식으로 저장합니다.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

임시 라이센스 신청

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

또한보십시오

I file di testo sono un tipo di file comune che contiene solo testo semplice senza formattazione o stili. Se desideri applicare la formattazione o aggiungere immagini, grafici, tabelle e altri elementi multimediali ai file di testo, una delle soluzioni consigliate è convertirli in file Word.

Al contrario, se desideri estrarre contenuti in modo efficiente o ridurre le dimensioni dei file dei documenti Word, puoi convertirli in formato testo. Questo articolo dimostrerà come farlo a livello di codice convertire file di testo in formato Word e convertire file di Word in formato testo utilizzando Spire.Doc for Python.

Installa Spire.Doc for Python

Questo scenario richiede Spire.Doc for Python e plum-dispatch v1.7.4. Possono essere facilmente installati nel tuo VS Code tramite i seguenti comandi pip.

pip install Spire.Doc

Se non sei sicuro su come installare, fai riferimento a questo tutorial: Come installare Spire.Doc for Python in VS Code

Converti testo (TXT) in Word in Python

La conversione da TXT a Word è abbastanza semplice e richiede solo poche righe di codice. Di seguito sono riportati i passaggi dettagliati.

  • Creare un oggetto Documento.
  • Carica un file di testo utilizzando il metodo Document.LoadFromFile(string fileName).
  • Salvare il file di testo come file Word utilizzando il metodo Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a TXT file
document.LoadFromFile("input.txt")

# Save the TXT file as Word
document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
document.Close()

Python: Convert Text to Word or Word to Text

Converti Word in testo (TXT) in Python

Il metodo Document.SaveToFile(string fileName, FileFormat.Txt) fornito da Spire.Doc for Python consente di esportare un file Word in formato testo. Di seguito sono riportati i passaggi dettagliati.

  • Creare un oggetto Documento.
  • Carica un file Word utilizzando il metodo Document.LoadFromFile(string fileName).
  • Salvare il file Word in formato txt utilizzando il metodo Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file from disk
document.LoadFromFile("Input.docx")

# Save the Word file in txt format
document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
document.Close()

Python: Convert Text to Word or Word to Text

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Les fichiers texte sont un type de fichier courant qui contient uniquement du texte brut, sans aucun formatage ni style. Si vous souhaitez appliquer une mise en forme ou ajouter des images, des graphiques, des tableaux et d'autres éléments multimédias à des fichiers texte, l'une des solutions recommandées consiste à les convertir en fichiers Word.

À l’inverse, si vous souhaitez extraire efficacement du contenu ou réduire la taille des documents Word, vous pouvez les convertir au format texte. Cet article montrera comment par programmation convertissez des fichiers texte au format Word et convertissez des fichiers Word au format texte à l'aide de Spire.Doc for Python.

Installer Spire.Doc for Python

Ce scénario nécessite Spire.Doc for Python et plum-dispatch v1.7.4. Ils peuvent être facilement installés dans votre VS Code via les commandes pip suivantes.

pip install Spire.Doc

Si vous ne savez pas comment procéder à l'installation, veuillez vous référer à ce didacticiel : Comment installer Spire.Doc for Python dans VS Code

Convertir du texte (TXT) en Word en Python

La conversion de TXT en Word est assez simple et ne nécessite que quelques lignes de code. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un fichier texte à l’aide de la méthode Document.LoadFromFile(string fileName).
  • Enregistrez le fichier texte en tant que fichier Word à l'aide de la méthode Document.SaveToFile(string fileName, FileFormat fileFormat).
  • Python
from spire.doc import *
    from spire.doc.common import *
    
    # Create a Document object
    document = Document()
    
    # Load a TXT file
    document.LoadFromFile("input.txt")
    
    # Save the TXT file as Word
    document.SaveToFile("TxtToWord.docx", FileFormat.Docx2016)
    document.Close()

Python: Convert Text to Word or Word to Text

Convertir un mot en texte (TXT) en Python

La méthode Document.SaveToFile(string fileName, FileFormat.Txt) fournie par Spire.Doc for Python permet d'exporter un fichier Word au format texte. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un fichier Word à l’aide de la méthode Document.LoadFromFile(string fileName).
  • Enregistrez le fichier Word au format txt à l'aide de la méthode Document.SaveToFile(string fileName, FileFormat.Txt).
  • Python
from spire.doc import *
    from spire.doc.common import *
    
    # Create a Document object
    document = Document()
    
    # Load a Word file from disk
    document.LoadFromFile("Input.docx")
    
    # Save the Word file in txt format
    document.SaveToFile("WordToTxt.txt", FileFormat.Txt)
    document.Close()

Python: Convert Text to Word or Word to Text

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également