C++ Convert Between Word and TXT Documents

Plain text (TXT) contains only characters and line breaks. It carries no fonts, font sizes, tables or images, so the files are small and any program can read them; they are commonly used for log export, data exchange and content archiving. Word handles layout and formal delivery, and converting between the two formats is common: exporting Word to TXT extracts body text that a program can process further, and loading TXT as Word turns collected text into a regular document.

The boundary should be stated first: TXT has no concept of styles or structure, so both directions work only at the text level. Styles, table structure and images on the Word side do not enter the TXT; conversely, the Word document produced from TXT contains only ordinary paragraphs, and headings and lists have to be set separately. Using the conversion with this boundary in mind avoids unrealistic expectations about the result.

Spire.Doc for C++ exports plain text through FileFormat::Txt in Document->SaveToFile(), loads a text file as a document object through Document->LoadText(), and specifies the source file encoding through Encoding. All processing takes place in the local process, and the document does not need to be uploaded to any service.

This article covers three features:

The examples use the Quarterly Product Operations Meeting Minutes (WordToTxt.docx). The document runs to one page and contains a title, a bulleted list, a numbered list, one table, one bar chart, and a header and footer:

The Word document to be converted, one page in total

The reverse conversion uses the plain-text version of the same minutes (TxtToWord.txt). The file is UTF-8 encoded and has 25 lines, containing a title, section names, numbered lines and items that begin with a hyphen; it is used to check the paragraph mapping rules from TXT to Word.

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.

  • In Visual Studio, open the NuGet Package Manager, search for Spire.Doc.Cpp, and install it.
  • Alternatively, run nuget install Spire.Doc.Cpp in the project directory, and then add the package's include and lib folders to the project.

An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.

Convert Word to TXT

Exporting Word to plain text requires only specifying FileFormat::Txt at save time. The load step is unchanged: LoadFromFile() loads the Word document, the format enumeration at save time determines the output type, and Spire.Doc extracts the document content under the "text only" rule.

Operation Main call
Load a Word document Document->LoadFromFile(fileName)
Export plain text Document->SaveToFile(fileName, FileFormat::Txt)
Load plain text Document->LoadText(fileName)
Load plain text with an encoding Document->LoadText(fileName, encoding)

The detailed steps are as follows.

  • Create a Document object.
  • Load the sample Word file with the Document->LoadFromFile() method.
  • Call Document->SaveToFile() and save the document with FileFormat::Txt.
  • Call Document->Close() to release the document.

The code for converting Word to TXT is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

    // Specify the input file path
    string inputFile = "Data/WordToTxt.docx";

    // Specify the output file path and name
    string outputPath = "Output/";
    string outputFile = outputPath + "WordToTxt.txt";

    // Create a Document object and load the Word document
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile(inputFile);

    // Export the document as plain text
    document->SaveToFile(outputFile, FileFormat::Txt);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

The sample document is 55,520 bytes, and the exported plain text is 1,233 bytes. The original document is on the left and the exported result on the right; the title, the lists and the table keep only their text, and the image is not exported:

The Word document and the exported plain text

Export Rules

FileFormat::Txt extracts text in paragraph order; each element is handled as follows.

Element Export result
Title and body text Fonts, font sizes, colors and bold are discarded; written as ordinary text lines
Bulleted list Written with a * prefix; list level information is lost
Numbered list Written with a 1. prefix (digit, period and two spaces)
Table Expanded cell by cell into separate lines; row and column relationships are not preserved
Image Not exported; the paragraph that contains it becomes an empty line
Header and footer Header text is written on the first line, footer text on the last line

The table in the sample has four rows and three columns, so the twelve cells each occupy one line after export; the paragraph that contains the bar chart becomes an empty line; the header "Skylark Technology · Operations Center" is on the first line of the file, and the footer "Internal Use Only · Do Not Distribute" is on the last line. When row and column relationships have to be restored, regroup the lines by a fixed column count on the reading side instead of looking for a delimiter in the TXT.

Encoding and Line Breaks

The exported plain text is UTF-8 encoded with a BOM, the byte order mark is EF BB BF, and line breaks are CRLF. The BOM helps Windows Notepad and some editors identify the encoding, but programs that process bytes treat the BOM as characters at the start of the body and should remove it before reading. With std::ifstream, check the first three bytes and skip them, or decode the file as utf-8-sig.

Convert TXT to Word

Loading TXT as a Word document uses LoadText(). Unlike LoadFromFile(), LoadText() is dedicated to text files and provides an overload that accepts an Encoding parameter; after loading, call SaveToFile() to save the document as Docx and the Word document is ready.

The detailed steps are as follows.

  • Create a Document object.
  • Load the plain text file with the Document->LoadText() method.
  • Call Document->SaveToFile() and save the document with FileFormat::Docx2013.
  • Call Document->Close() to release the document.

The code for converting TXT to Word is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;

int main() {

    // Specify the input file path
    string inputFile = "Data/TxtToWord.txt";

    // Specify the output file path and name
    string outputPath = "Output/";
    string outputFile = outputPath + "TxtToWord.docx";

    // Create a Document object
    intrusive_ptr<Document> document = new Document();

    // Load the plain text file
    document->LoadText(inputFile);

    // Save the document as Word (docx)
    document->SaveToFile(outputFile, FileFormat::Docx2013);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

The loaded text is restored as paragraphs line by line, all in the Normal style, and the title and list markers remain as ordinary text:

The plain text and the Word document produced from it

Paragraph Mapping Rules

The sample text has 25 lines, and the loaded document contains 26 paragraphs. Each line break corresponds to one paragraph, and an empty line corresponds to an empty paragraph; the line break at the end of the file produces one more empty paragraph at the end, so the paragraph count is one higher than the line count.

The loading process does not interpret any Markdown or plain-text layout conventions: I. Meeting Overview is ordinary text and does not become a heading; 1. and - are only line-start characters and do not produce numbered or bulleted lists; spaces within a line and typographic punctuation are kept as they are. If headings and lists are needed after conversion, reset the style of the specified paragraphs according to a fixed line format, or use an input format that carries structure.

Choosing Between LoadText and LoadFromFile

LoadFromFile(fileName, FileFormat::Txt) can also load a text file, and LoadFromFile(fileName) can be used directly when the extension is recognized. Both methods produce the same document content as LoadText(); the difference is that LoadText() provides the encoding parameter and suits files that are not UTF-8 or scenarios that require a fixed decoding behavior. For files whose extension is not .txt, prefer LoadText() or specify FileFormat::Txt explicitly to avoid a failure of extension-based recognition.

Load a TXT File with a Specified Encoding

A text file carries no encoding declaration, and the same byte sequence decodes into different characters under different encodings. Legacy files from Chinese Windows environments often use GBK, files exported by cross-platform tools are mostly UTF-8, and some systems also output UTF-16 or UTF-7. When the encoding is wrong, characters appear as mojibake or replacement characters.

The second parameter of LoadText() accepts an Encoding object that specifies the source file encoding. Spire::Doc::Common::Encoding provides factory methods for common encodings and can also construct one from a code page.

Encoding Code page Factory method
UTF-8 65001 Encoding::GetUTF8()
GBK 936 Encoding::GetEncoding(936)
UTF-16 LE 1200 Encoding::GetUnicode()
UTF-16 BE 1201 Encoding::GetBigEndianUnicode()
UTF-7 65000 Encoding::GetUTF7()
UTF-32 12000 Encoding::GetUTF32()

The detailed steps are as follows.

  • Create a Document object.
  • Load the text file with the Document->LoadText() method, passing Encoding::GetUTF8() as the second parameter.
  • Call Document->SaveToFile() and save the document with FileFormat::Docx2013.
  • Call Document->Close() to release the document.

The code for loading plain text as UTF-8 is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/FileFormat.h"
#include "Spire/Doc/common/h/Encoding.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;

int main() {

    // Specify the input file path
    string inputFile = "Data/TxtToWord.txt";

    // Specify the output file path and name
    string outputFile = "Output/TxtToWord_Utf8.docx";

    // Create a Document object
    intrusive_ptr<Document> document = new Document();

    // Load the plain text with UTF-8 encoding
    document->LoadText(inputFile, Encoding::GetUTF8());

    // To read a GBK file, use the 936 code page instead
    // document->LoadText("Data/TxtToWord_GBK.txt", Encoding::GetEncoding(936));

    // Save as a Word document
    document->SaveToFile(outputFile, FileFormat::Docx2013);

    document->Close();

    cout << "Saved: " << outputFile << endl;
}

Symptoms of an Encoding Mismatch

Decoding the same UTF-8 file as GBK and saving the result as Word turns the accented name and the typographic punctuation in the document into unrelated characters and replacement symbols, for example Jos茅 脕lvarez in place of José Álvarez; the ASCII text around them remains readable, so the error can hide in names and quotes. Decoding as UTF-8 is correct. The left side shows the wrong encoding and the right side the correct result:

The same file decoded as GBK and as UTF-8

When this kind of result appears, check the actual encoding of the file rather than modifying the document content. A hex viewer shows the bytes: non-ASCII UTF-8 characters start with C2–F4, GBK lead bytes are 81–FE, and files with a BOM begin with EF BB BF (UTF-8), FF FE (UTF-16 LE) or FE FF (UTF-16 BE).

Default Loading and Explicit Encoding

Without an encoding, LoadText() recognizes common encodings from the file content. In the sample environment, UTF-8, GBK and UTF-16 files load correctly when no Encoding argument is passed. A UTF-7 file whose content starts with ASCII is not recognized: the escape sequences remain in the text, and the file has to be loaded with Encoding::GetUTF7(), which decodes it correctly. The recognition strategy may differ between runtime versions, so when the file encoding is uncommon, or when the result must be identical on every load, pass Encoding explicitly so that decoding does not depend on the environment.

Function Comparison

Function Main call Key point
Word to TXT SaveToFile(..., FileFormat::Txt) Text only; UTF-8 with BOM, CRLF
TXT to Word LoadText(fileName) + Docx2013 One paragraph per line break, all in Normal style
Load with an encoding LoadText(fileName, encoding) The encoding must match the file

Both directions handle text only. Word to TXT loses tables, images and styles; TXT to Word does not create headings or lists automatically. When the same content has to move back and forth between the two formats, keep a structured original document and use the TXT only as a text carrier.

Get a Free License

If you want to remove the evaluation message from the generated documents, or to get rid of the function limitations, please apply for a 30-day temporary license.