C++: Create or Edit Excel Files

Excel files are files created by Microsoft Excel or other spreadsheet programs. They enable users to easily store, organize and analyze data in tabular form. Today, Excel files are widely used in various industries for data management, budgeting, accounting, statistical data analysis, and more. In this article, you will see how to create or edit Excel files using C++.

C++ Library to Create or Edit Excel Files

In order to create or edit Excel files in C++ applications, this article uses a third-party library — Spire.XLS for C++. Spire.XLS for C++ is a professional Excel API that can be applied to create, write, edit, convert, and read Excel files in C++ applications.

NuGet is the easiest way to integrate Spire.XLS for C++ into your application, and there are two ways to install Spire.XLS for C++ through NuGet.

1. Install Spire.XLS for C++ using Manage NuGet Packages.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
  • Search for “Spire.XLS.Cpp” and click install.

2. Install Spire.XLS for C++ using Package Manager Console.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Package Manager Console.
  • Type the command “Install-Package Spire.XLS.Cpp” and press enter.

If you can’t install the library through NuGet, you can download the package from the official site and manually import it into your project. For more details, you can check the documentation — How to Integrate Spire.XLS for C++ in a C++ Application.

Create Excel XLS or XLSX Files using C++

You can create Excel files with a wide variety of elements using Spire.XLS for C++, such as text, numeric data, images, formulas, hyperlinks, comments, shapes, and charts. The following steps explain how to create a simple Excel file with text and numeric data:

  • Initialize an instance of the Workbook class.
  • Get a specific worksheet by its index (zero-based) using Workbook->GetWorksheets()->Get(int) method (by default, a newly created workbook has 3 worksheets).
  • Add some text and numeric data to specific cells of the worksheet using Worksheet->GetRange(int, int)->SetText() and Worksheet->GetRange(int, int)->SetNumberValue() methods.
  • Set style for the header row and the remaining rows respectively.
  • Autofit column width using Worksheet->GetAllocatedRange()->AutoFitColumns() method.
  • Save the file to an XLS or XLSX file using Workbook->SaveToFile (LPCWSTR_S, ExcelVersion) method.
#include "Spire.Xls.o.h";

using namespace Spire::Xls;

int main()
{
    //Initialize an instance of the Workbook class
    Workbook* workbook = new Workbook();
	//Get the first worksheet (by default, a newly created workbook has 3 worksheets)
    Worksheet* sheet = workbook->GetWorksheets()->Get(0);

	//Add some text and numeric data to specific cells of the first worksheet
	sheet->GetRange(1, 1)->SetText(L"Department");
	sheet->GetRange(2, 1)->SetText(L"Accounting and Finance");
	sheet->GetRange(3, 1)->SetText(L"Research and Development");
	sheet->GetRange(4, 1)->SetText(L"Human Resources");
	sheet->GetRange(5, 1)->SetText(L"Sales");
	sheet->GetRange(1, 2)->SetText(L"Name");
	sheet->GetRange(2, 2)->SetText(L"Martin");
	sheet->GetRange(3, 2)->SetText(L"Patrick");
	sheet->GetRange(4, 2)->SetText(L"Karen");
	sheet->GetRange(5, 2)->SetText(L"Anthony");
	sheet->GetRange(1, 3)->SetText(L"Salary");
	sheet->GetRange(2, 3)->SetNumberValue(6100);
	sheet->GetRange(3, 3)->SetNumberValue(7800);
	sheet->GetRange(4, 3)->SetNumberValue(5400);
	sheet->GetRange(5, 3)->SetNumberValue(7400);

	//Get row count
	int rowCount = sheet->GetRows()->GetCount();
	//Get column count
	int colCount = sheet->GetColumns()->GetCount();

	//Iterate through the rows and columns in the worksheet
	for (int row = 1; row <= rowCount; row++)
	{
		for (int col = 1; col <= colCount; col++)
		{	//Set style for cells of the header row	
			sheet->GetRange(1, col)->GetStyle()->GetFont()->SetFontName(L"Calibri");
			sheet->GetRange(1, col)->GetStyle()->GetFont()->SetSize(12);
			sheet->GetRange(1, col)->GetStyle()->GetFont()->SetIsBold(true);
			sheet->GetRange(1, col)->GetStyle()->SetHorizontalAlignment(HorizontalAlignType::Center);
			sheet->GetRange(1, col)->GetStyle()->SetVerticalAlignment(VerticalAlignType::Center);

			//Set style for cells of the remaining rows
			sheet->GetRange(row + 1, col)->GetStyle()->GetFont()->SetFontName(L"Calibri");
			sheet->GetRange(row + 1, col)->GetStyle()->GetFont()->SetSize(11);
			sheet->GetRange(row + 1, col)->GetStyle()->SetHorizontalAlignment(HorizontalAlignType::Center);
			sheet->GetRange(row + 1, col)->GetStyle()->SetVerticalAlignment(VerticalAlignType::Center);
		}
	}

	//Autofit column width
	sheet->GetAllocatedRange()->AutoFitColumns();

	//Save the file to an XLSX file
	workbook->SaveToFile(L"CreateExcel.xlsx", ExcelVersion::Version2013);
	//Save the file to an XLS file
	//workbook->SaveToFile(L"CreateExcel.xls", ExcelVersion::Version97to2003);
	workbook->Dispose();
	delete workbook;
}
Create Excel File in C++

Edit Excel XLS or XLSX Files using C++

You can also edit or update existing Excel files using Spire.XLS for C++. The steps below explain how to update the text of a specific cell and set a background color for it:

  • Initialize an instance of the Workbook class.
  • Load an XLS or XLSX File using Workbook->LoadFromFile() method.
  • Get a specific worksheet by its index (zero-based) using Workbook->GetWorksheets()->Get(int) method.
  • Edit the text of a specific cell using Worksheet->GetRange(int, int)->SetText() method.
  • Set a background color for the cell using Worksheet->GetRange(int, int)-> GetStyle()->SetColor() method.
  • Save the file to an XLS or XLSX file using Workbook->SaveToFile (LPCWSTR_S, ExcelVersion) method.
#include "Spire.Xls.o.h";

using namespace Spire::Xls;
using namespace Spire::Common;

int main()
{
	//Initialize an instance of the Workbook class
	Workbook* workbook = new Workbook();
	//Load an XLSX or XLS file
	workbook->LoadFromFile(L"CreateExcel.xlsx");
	//workbook->LoadFromFile(L"CreateExcel.xls");
	
	//Get the first worksheet
	Worksheet* sheet = workbook->GetWorksheets()->Get(0);
	
	//Update the text of the cell [2, 1]
	sheet->GetRange(2, 1)->SetText(L"Updated Cell");
	//Set a background color for the cell [2, 1]
	sheet->GetRange(2, 1)->GetStyle()->SetColor(Color::GetMediumSpringGreen());

	//Save the file to an XLSX file
	workbook->SaveToFile(L"EditExcel.xlsx", ExcelVersion::Version2013);
	//Save the file to an XLS file
	//workbook->SaveToFile(L"EditExcel.xls", ExcelVersion::Version97to2003);
	workbook->Dispose();
	delete workbook;
}
Edit Excel File in C++

C++: Create PDF Files

PDF stands for Portable Document Format, which is a standardized and versatile file format developed by Adobe in 1992. PDF files have many advantages, for example, they can be opened on almost any hardware or operating system without the need for a PDF reader, their layout can remain unchanged no matter what hardware or operating system is used to open them, and their content is not easy to edit. This article will demonstrate how to programmatically create PDF Files using C++.

C++ Library to Create PDF Files

In order to create PDF files in C++ applications, this article uses a third-party library – Spire.PDF for C++. Spire.PDF for C++ is a professional PDF API that can be applied to create, write, edit, convert, and read PDF files in C++ applications.

NuGet is the easiest way to integrate Spire.PDF for C++ into your application, and there are two ways to install Spire.PDF for C++ through NuGet.

1. Install Spire.PDF for C++ using Manage NuGet Packages.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
  • Search for “Spire.PDF.Cpp” and click install.

2. Install Spire.PDF for C++ using Package Manager Console.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Package Manager Console.
  • Type the command “Install-Package Spire.PDF.Cpp” and press enter.

In case you can’t install the library through NuGet, you can download the package from the official site and then manually import it into your project. For more details, you can check the documentation — How to Integrate Spire.PDF for C++ in a C++ Application.

Create PDF Files in C++

A PDF file can contain a wide variety of elements, such as text, images, tables, hyperlinks, signatures, fillable form fields, attachments and annotations. The following steps will explain how to create a simple PDF file with text and image:

  • Create a PdfDocument instance.
  • Add a page using PdfDocument->GetPages()->Add() method.
  • Create two PdfSolidBrush instances.
  • Create two PdfTrueTypeFont instances.
  • Create a PdfStringFormat instance and set the text alignment to center using PdfStringFormat ->SetAlignment(PdfTextAlignment::Center) method.
  • Specify the title text.
  • Draw title text on the center of the page with specific brush, font, and string format using PdfPageBase->GetCanvas()->DrawString() method.
  • Specify body text.
  • Create a PdfTextWidget instance based on the body text.
  • Create a RectangleF instance which will then be used to specify the page area for drawing body text.
  • Create a PdfTextLayout instance and set the layout type to paginate to make the content paginated automatically.
  • Draw body text on specific area of the page using PdfTextWidget.Draw() method.
  • Create a PdfImage instance and load an image using PdfImage->FromFile() method.
  • Draw image on the page using PdfPageBase->GetCanvas()->DrawImage() method.
  • Save the result file using PdfDocument->SaveToFile() method.
#include "Spire.Pdf.o.h";

using namespace Spire::Pdf;
using namespace Spire::Common;
using namespace std;

int main()
{
    //Create a PdfDocument instance
    PdfDocument* pdf = new PdfDocument();
    //Add a page
    PdfPageBase* page = pdf->GetPages()->Add();

    //Create two PdfSolidBrush instances
    PdfSolidBrush* brush1 = new PdfSolidBrush(new PdfRGBColor(Color::GetBlue()));
    PdfSolidBrush* brush2 = new PdfSolidBrush(new PdfRGBColor(Color::GetBlack()));

    //Create two PdfTrueTypeFont instances
    PdfTrueTypeFont* font1 = new PdfTrueTypeFont(L"Times New Roman", 20, PdfFontStyle::Bold, true);
    PdfTrueTypeFont* font2 = new PdfTrueTypeFont(L"Times New Roman", 12, PdfFontStyle::Regular, true);

    //Create a PdfStringFormat instance
    PdfStringFormat* format = new PdfStringFormat();
    //Set the text alignment to center
    format->SetAlignment(PdfTextAlignment::Center);

    //Specify title text
    wstring title = L"Introduction to C++ Programming Language";

    //Draw title on the center of the page
    page->GetCanvas()->DrawString(title.c_str(), font1, brush1, new PointF((float)page->GetCanvas()->GetClientSize()->GetWidth() / 2, 20), format);

    //Specify body text
    wstring body = L"C++ (pronounced C plus plus) is a computer programming language based on C. It was created for writing programs for many different purposes. In the 1990s, C++ became one of the most used programming languages in the world.";

    //Create a PdfTextWidget instance
    PdfTextWidget* widget = new PdfTextWidget(body.c_str(), font2, brush2);
    //Create a RectangleF instance
    RectangleF* rect = new RectangleF(new PointF(0, 50), new SizeF((float)page->GetCanvas()->GetClientSize()->GetWidth(), (float)page->GetCanvas()->GetClientSize()->GetHeight()));

    //Create a PdfTextLayout instance
PdfTextLayout* layout = new PdfTextLayout();
    //Set the PdfLayoutType to Paginate to make the content paginated automatically
    layout->SetLayout(PdfLayoutType::Paginate);

    PdfNewPage* newPage = Object::Convert<PdfNewPage>(page);

    //Draw body text on the page
    widget->Draw(newPage, rect, layout);

    //Load an image
    PdfImage* image = new PdfImage();
    image = image->FromFile(L"C++.png");
    float width = image->GetWidth()*0.35;
    float height = image->GetHeight()*0.35;
    float x = (page->GetCanvas()->GetClientSize()->GetWidth() - width) / 2;

    //Draw image on the page
    page->GetCanvas()->DrawImage(image, x, 100, width, height);

    //Save the result file
    pdf->SaveToFile(L"CreatePdf.pdf");
    pdf->Close();
    delete pdf;
    delete brush1;
    delete brush2;
    delete font1;
    delete font2;
    delete format;
    delete widget;
    delete rect;
    delete layout;
    delete image;
}
Create PDF File in C++

Convert RTF to Word or Word to RTF in C++

RTF stands for Rich Text Format, which is a proprietary file format developed by Microsoft for exchanging text files between different word processing programs. Unlike Word documents, RTF is readable across many programs and platforms, but it has some limitations, for example, it cannot retain certain types of formatting, such as track changes and comments, or include certain types of images. Sometimes, you may need to convert an RTF file to Word to get rid of these limitations or convert a Word file to RTF to improve its compatibility. In this article, I will demonstrate how to programmatically convert RTF files to Word or convert Word files to RTF in C++.

  • Convert RTF to Word in C++
  • Convert Word to RTF in C++

C++ Library to Convert RTF to Word or Word to RTF

In order to implement the conversions between RTF and Word files in C++ applications, this article uses a third-party library called Spire.Doc for C++. Spire.Doc for C++ is a professional Word library specifically designed for creating, reading, writing, converting, merging, splitting, and comparing Word documents in C++ applications with fast and high-quality performance.

NuGet is the easiest way to integrate Spire.Doc for C++ into your application, and there are two ways to install Spire.Doc for C++ through NuGet.

1. Install Spire.Doc for C++ using Manage NuGet Packages.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…
  • Search for Spire.Doc.Cpp and click install.

2. Install the library using Package Manager Console.

  • Create or open your project in Visual Studio.
  • Click Tools -> NuGet Package Manager -> Package Manager Console.
  • Type the command “Install-Package Spire.Doc.Cpp” and press enter.

In case you can’t install the library through NuGet, you can download the package from the official site and then manually import it into your project. For more details, you can check the documentation – How to Integrate Spire.Doc for C++ in a C++ Application.

Convert RTF to Word in C++

Converting an RTF file to Word is very straightforward with Spire.Doc for C++, you just need to load the file and then call the Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method. The following steps show you how to convert RTF to Word in C++:

  • Initialize an instance of the Document class.
  • Load an RTF document using Document->LoadFromFile(LPCWSTR_S fileName) method.
  • Save the RTF document to Word Doc/Docx format using Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
#include "Spire.Doc.o.h"

using namespace Spire::Doc;

int main()
{
	//Initialize an instance of the document class
	Document* doc = new Document();
	//Load an RTF file 
	doc->LoadFromFile(L"Input.rtf");

	//Save the RTF file to Word Docx format
	doc->SaveToFile(L"RtfToWord.docx", FileFormat::Docx2013);
	doc->Close();
	delete doc;
}

Convert Word to RTF in C++

The Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method can also be used to convert a Word file to RTF format. The steps to convert a Word file to RTF are very similar to that of the above example:

  • Initialize an instance of the Document class.
  • Load a Word document using Document->LoadFromFile(LPCWSTR_S fileName) method.
  • Save the document as an RTF file using Document->SaveToFile(LPCWSTR_S fileName, FileFormat fileFormat) method.
#include "Spire.Doc.o.h"

using namespace Spire::Doc;

int main()
{
	//Initialize an instance of the document class
	Document* doc = new Document();
	//Load a Word file 
	doc->LoadFromFile(L"Input.docx");

	//Save the Word file to RTF format
	doc->SaveToFile(L"WordToRtf.docx", FileFormat::Rtf);
	doc->Close();
	delete doc;
}

Conclusion

This article demonstrated how to convert RTF to Word or Word to RTF in C++ applications using Spire.Doc for C++. Actually, this library also supports lots of other file format conversions, for example, it can convert RTF to PDF and HTML, as well as convert Word to HTML, PDF, images and more.

C#/VB.NET: Convert Excel XLS to XLSX or XLSX to XLS

XLS and XLSX are two file formats used by Microsoft Excel to store spreadsheet data. XLS files can be opened by Excel 2007 and later versions, but XLSX files cannot be opened by Excel 2003 and earlier versions due to compatibility problems. Microsoft Excel provides users with a “Save As” function, which can save XLS files in XLSX format or XLSX files in XLS format. However, as a developer, you may need to implement the conversion programmatically. In this article, I will demonstrate how to convert Excel XLS to XLSX or XLSX to XLS in C# and VB.NET.

C# Library to Convert Excel XLS to XLSX or XLSX to XLS

In order to convert between Excel XLS and XLSX, this article uses Spire.XLS for .NET library. You can install Spire.XLS for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.XLS

Alternatively, you can also download the API from the official site and extract the package, then add the DLL files under the BIN folder to your project as references.

Convert Excel XLS to XLSX in C# and VB.NET:

The Workbook.SaveToFile(string filePath, ExcelVersion version) method can be used to convert between different Excel versions. To convert an XLS file to XLSX format, you need to specify the ExcelVersion as Version2007/Version2010/Version2013/Version2016. The following steps show you how to convert an XLS file to XLSX (version 2016):

  • Initialize an instance of the Workbook class.
  • Load an XLS file using Workbook.LoadFromFile(string filePath) method.
  • Save the XLS file to XLSX format using Workbook.SaveToFile(string filePath, ExcelVersion.Version2016) method.

C#

using Spire.Xls;

namespace ConvertXlsToXlsx
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load an XLS file
            workbook.LoadFromFile("Input.xls");

            //Save the XLS file to XLSX format
            workbook.SaveToFile("ToXLSX.xlsx", ExcelVersion.Version2016);
            workbook.Dispose();
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace ConvertXlsToXlsx
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Workbook class
            Dim workbook As Workbook = New Workbook()
            'Load an XLS file
            workbook.LoadFromFile("Input.xls")

            'Save the XLS file to XLSX format
            workbook.SaveToFile("ToXLSX.xlsx", ExcelVersion.Version2016)
            workbook.Dispose()
        End Sub
    End Class
End Namespace

Convert Excel XLSX to XLS in C# and VB.NET

To convert an Excel XLSX file to XLS format, you can also use the Workbook.SaveToFile(string filePath, ExcelVersion version) method. The steps are almost the same as that of converting XLS to XLSX, the difference is that you need to specify the ExcelVersion as Version97to2003:

  • Initialize an instance of the Workbook class.
  • Load an XLSX file using Workbook.LoadFromFile(string filePath) method.
  • Save the XLSX file to XLS format using Workbook.SaveToFile(string filePath, ExcelVersion.Version97to2003) method.

C#

using Spire.Xls;

namespace ConvertBetweenXlsAndXlsx
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Workbook class
            Workbook workbook = new Workbook();
            //Load an XLSX file
            workbook.LoadFromFile("Input.xlsx");

            //Save the XLSX file to XLS format
            workbook.SaveToFile("ToXLS.xls", ExcelVersion.Version97to2003);
            workbook.Dispose();
        }
    }
}

VB.NET

Imports Spire.Xls

Namespace ConvertBetweenXlsAndXlsx
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Workbook class
            Dim workbook As Workbook = New Workbook()
            'Load an XLSX file
            workbook.LoadFromFile("Input.xlsx")

            'Save the XLSX file to XLS format
            workbook.SaveToFile("ToXLS.xls", ExcelVersion.Version97to2003)
            workbook.Dispose()
        End Sub
    End Class
End Namespace

Conclusion

This article introduced how to convert XLS to XLSX or XLSX to XLS in C# and VB.NET using the Workbook.SaveToFile(string, ExcelVersion) method provided by Spire.XLS for .NET. In addition to that, you can also use the same method to convert from XLS or XLSX to other spreadsheet formats such as XLSB, ODS and UOS.

C#/VB.NET: Generate or Scan QR Code

What is a QR Code

A QR code is a machine-readable code consisting of an array of black and white squares, typically used for storing URL or other information for reading by the camera on a smartphone. The QR code system was invented in 1994, now it’s popular worldwide due to its faster readability and greater storage capacity compared to standard UPC barcodes.

In this article, I will demonstrate how to generate or scan QR code using C# and VB.NET.

C# Library to Generate or Scan QR Code

In order to generate or scan QR code, I will use Spire.Barcode for .NET API which supports generating and reading up to 39 kinds of 1D and 2D barcodes.

You can either download the API from here or install it via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console and then adding the following code:

PM> Install-Package Spire.Barcode

Generate QR Code in C# and VB.NET

The following steps show you how to generate a QR code using C# and VB.NET:

  • Initialize an instance of the BarcodeSettings class.
  • Specify the barcode type as QR code by setting the BarcodeSettings.Type property as BarCodeType.QRCode.
  • Set other properties such as error collection level, barcode module width, and data for the QR code using BarcodeSettings.QRCodeECL, BarcodeSettings.X and BarcodeSetting.Data properties.
  • Initialize an instance of the BarCodeGenerator class.
  • Generate QR code image using BarCodeGenerator.GenerateImage() method.
  • Save the image to file using System.Drawing.Image.Save() method.

C#

using Spire.Barcode;
using System.Drawing;

namespace GenerateQRCode
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the BarcodeSettings class
            BarcodeSettings barcodeSettings = new BarcodeSettings
            {
                //Specify the barcode type as QRCode
                Type = BarCodeType.QRCode,
                //Set error collection level
                QRCodeECL = QRCodeECL.M,
                //Set width of the barcode module
                X = 2.5f,
                //Set barcode data 
                Data = "https://medium.com/",
                //Set text to display on top of the barcode (By default, it's the same as the barcode data)
                //Data2D = "Medium",
                //Hide text from barcode
                ShowText = false,
            };

            //Initialize an instance of the BarCodeGenerator class
            BarCodeGenerator barCodeGenerator = new BarCodeGenerator(barcodeSettings);
            //Generate QRCode image
            Image image = barCodeGenerator.GenerateImage();
            //Save the image to file
            image.Save("QRCode.png");
        }
    }
}

VB.NET

Imports Spire.Barcode

Namespace GenerateQRCode
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the BarcodeSettings class
            Dim barcodeSettings As BarcodeSettings = New BarcodeSettings With {
    'Specify the barcode type as QRCode
    .Type = BarCodeType.QRCode,
    'Set error collection level
    .QRCodeECL = QRCodeECL.M,
    'Set width of the barcode module
    .X = 2.5F,
    'Set barcode data 
    .Data = "https://medium.com/",
    'Set text to display on top of the barcode (By default, it's the same as the barcode data)
    'Data2D = "Medium",
    'Hide text from barcode
    .ShowText = False
}

            'Initialize an instance of the BarCodeGenerator class
            Dim barCodeGenerator As BarCodeGenerator = New BarCodeGenerator(barcodeSettings)
            'Generate QRCode image
            Dim image As Image = barCodeGenerator.GenerateImage()
            'Save the image to file
            image.Save("QRCode.png")
        End Sub
    End Class
End Namespace
Generate QR code in C#

Scan QR Code in C# and VB.NET

The following steps show you how to scan a QR code image using C# and VB.NET:

  • Scan the QR code image using BarcodeScanner.ScanOne(string filePath) method and save the result into a string object.
  • Print out the result using Console.WriteLine() method.

C#

using Spire.Barcode;

namespace ScanQRCode
{
    internal class Program
    {
        static void Main(string[] args)
        {          
            //Scan the QR code image
            string barcodeData = BarcodeScanner.ScanOne("QRCode.png");
            //Print out the result
            Console.WriteLine(barcodeData);
            Console.ReadKey();
        }
    }
}

VB.NET

Imports Spire.Barcode

Namespace ScanQRCode
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Scan the QR code image
            Dim barcodeData As String = BarcodeScanner.ScanOne("QRCode.png")
            'Print out the result
            Console.WriteLine(barcodeData)
            Console.ReadKey()
        End Sub
    End Class
End Namespace
Scan or Read QR Code in C#

In case you have an image that contains multiple barcodes, and you want to read the data of all the QR codes in the image, you can use the following code:

C#

using Spire.Barcode;

namespace ScanQRCodes
{
    internal class Program
    {
        static void Main(string[] args)
        {        
            //Scan the QR code image and save the data into a string array
            string[] results = BarcodeScanner.Scan("Barcodes.png", BarCodeType.QRCode);

            //Iterate through the array
            foreach (string result in results)
            {
                //Print out the result
                Console.WriteLine(result);
            }

            Console.ReadKey();
        }
    }
}

VB.NET

Imports Spire.Barcode

Namespace ScanQRCodes
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Scan the QR code image and save the data into a string array
            Dim results As String() = BarcodeScanner.Scan("Barcodes.png", BarCodeType.QRCode)

            'Iterate through the array
            For Each result In results
                'Print out the result
                Console.WriteLine(result)
            Next

            Console.ReadKey()
        End Sub
    End Class
End Namespace

Get a Free Trial License

The library will generate an evaluation message on the generated QR code image, you can request a free 30 days trial license to remove the messsage from the image.

C#/VB.NET: Extract or Read Text from Word Documents

Text is the main element of a Word document. In some cases, you might need to extract text content from Word documents to perform text analysis or to use it elsewhere. In this article, I will demonstrate how to extract text from Word documents in C# and VB.NET.

Installation

To extract text from Word documents, this article uses Spire.Doc for .NET. You can install Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.Doc

Alternatively, you can also download the DLL files of Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Extract Text from Word Documents in C# and VB.NET

Spire.Doc mainly provides two approaches to extracting text from a Word document. One is to directly get the text from the document using the Document.GetText() method, and the other is to iterate through all sections and paragraphs in the document and then extract text from each paragraph through Paragraph.Text property. The latter approach is more flexible than the former one since it allows you to extract text from a specific section or paragraph.

Approach 1 – Extract Text from a Word Document using Document.GetText() Method

The steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the text content from the document using Document.GetText() method.
  • Write the text content into a txt file using File.WriteAllText() method.

C#

using Spire.Doc;

namespace ExtractTextFromWord
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();
            //Load a Word document
            doc.LoadFromFile("Input.docx");

            //Get the text content from the document
            string content = doc.GetText();

            //Write the text content into a txt file
            File.WriteAllText("Extract1.txt", content);
        }
    }
}

VB.NET

Imports Spire.Doc

Namespace ExtractTextFromWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Input.docx")

            'Get the text content from the document
            Dim content As String = doc.GetText()

            'Write the text content into a txt file
            File.WriteAllText("Extract1.txt", content)
        End Sub
    End Class
End Namespace

Approach 2 – Extract Text from a Word Document by Iterating Through Sections and Paragraphs

The steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Initialize an instance of the StringBuilder class.
  • Iterate through all sections in the document.
  • Iterate through all paragraphs in each section.
  • Get text from each paragraph through Paragraph.Text property and save it to the string builder.
  • Write the text content into a txt file using File.WriteAllText() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.Text;

namespace ExtractTextFromWord
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();
           //Load a Word document
           doc.LoadFromFile("Input.docx");

            //Initialize an instance of the StringBuilder class
            StringBuilder sb = new StringBuilder();

            //Iterate through all sections in the document        
            for (int i = 0; i < doc.Sections.Count; i++)
            {
                Section section = doc.Sections[i];
                //Iterate through all paragraphs in each section    
                for (int j = 0; j < section.Paragraphs.Count; j++)
                {
                    Paragraph paragraph = section.Paragraphs[j];
                    //Get text from each paragraph and save it to the string builder
                    sb.AppendLine(paragraph.Text);
                }
            }

            //Write the text in the string builder into a txt file
            File.WriteAllText("Extract2.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Text

Namespace ExtractTextFromWord
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()
            'Load a Word document
            doc.LoadFromFile("Input.docx")

            'Initialize an instance of the StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Iterate through all sections in the document        
            For i As Integer = 0 To doc.Sections.Count - 1
                Dim section As Section = doc.Sections(i)
                'Iterate through all paragraphs in each section    
                For j As Integer = 0 To section.Paragraphs.Count - 1
                    Dim paragraph As Paragraph = section.Paragraphs(j)
                    'Get text from each paragraph and save it to the string builder
                    sb.AppendLine(paragraph.Text)
                Next
            Next

            'Write the text in the string builder into a txt file
            File.WriteAllText("Extract2.txt", sb.ToString())
        End Sub
    End Class
End Namespace
Design a site like this with WordPress.com
Get started