C++: Apply Fonts to Excel Cells

2023-04-04 00:52:52 Written by Koohji

While creating a worksheet, the default font MS Excel uses is "Calibri" with a size of 11 and a color of black. However, there are times when you may want to apply a different font style such as bold, italic to optimize the appearance of your document, or set a unique font color to highlight useful information within a large set of data. In this article, you will learn how to programmatically apply multiple font styles to Excel cells using Spire.XLS for C++.

Install Spire.XLS for C++

There are two ways to integrate Spire.XLS for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.XLS for C++ in a C++ Application

Apply Different Fonts to Different Excel Cells in C++

The ExcelFont class provided by Spire.XLS for C++ allows you to set or change the font name, color, size, and style in a cell easily. The following are the steps to apply different fonts to different cells in Excel.

  • Create a Workbook object.
  • Get a specific worksheet using Workbook->GetWorksheets()->Get() method.
  • Get a specified cell using Worksheet->GetRange() method.
  • Set the value of the cell using CellRange->SetText() method.
  • Get the font in the specified cell using CellRange->GetStyle()->GetFont() method.
  • Set the font name, color, size and style using the methods under the ExcelFont class.
  • Save the result file using Workbook->SaveToFile() method.
  • C++
#include "Spire.Xls.o.h";

using namespace Spire::Xls;

int main() {

	//Specify output file path and name
	std::wstring outputPath = L"Output\\";
	std::wstring outputFile = outputPath + L"ApplyFontToCell.xlsx";

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

	//Get the first worksheet
	Worksheet* sheet = workbook->GetWorksheets()->Get(0);

	//Set font name
	sheet->GetRange(L"B1")->SetText(L"Font name: Comic Sans MS");
	sheet->GetRange(L"B1")->GetStyle()->GetFont()->SetFontName(L"Comic Sans MS");

	//Set font size
	sheet->GetRange(L"B2")->SetText(L"Font size: 25");
	sheet->GetRange(L"B2")->GetStyle()->GetFont()->SetSize(25);

	//Set text to bold
	sheet->GetRange(L"B3")->SetText(L"Font style: Bold");
	sheet->GetRange(L"B3")->GetStyle()->GetFont()->SetIsBold(true);

	//Underline text
	sheet->GetRange(L"B4")->SetText(L"Font style: Underline");
	sheet->GetRange(L"B4")->GetStyle()->GetFont()->SetUnderline(FontUnderlineType::Single);

	//Set font color
	sheet->GetRange(L"B5")->SetText(L"Font color: Red");
	sheet->GetRange(L"B5")->GetStyle()->GetFont()->SetColor(Spire::Common::Color::GetRed());

	//Set text to italic
	sheet->GetRange(L"B6")->SetText(L"Font style: Italic");
	sheet->GetRange(L"B6")->GetStyle()->GetFont()->SetIsItalic(true);

	//Add strikethrough to text
	sheet->GetRange(L"B7")->SetText(L"Font style: Strikethrough");
	sheet->GetRange(L"B7")->GetStyle()->GetFont()->SetIsStrikethrough(true);

	//Save the result file
	workbook->SaveToFile(outputFile.c_str(), ExcelVersion::Version2013);
	workbook->Dispose();
}

C++: Apply Fonts to Excel Cells

Apply Multiple Fonts to a Single Excel Cell in C++

Mixing different fonts in one cell can help you emphasize some specific characters. The following are the steps to apply multiple fonts in an Excel cell.

  • Create a Workbook object.
  • Get a specific worksheet using Workbook->GetWorksheets()->Get() method.
  • Create two ExcelFont objects using Workbook->CreateExcelFont() method.
  • Get a specified cell using Worksheet->GetRange() method, and then set the rich text content of the cell using CellRange->GetRichText()->SetText() method.
  • Apply the two ExcelFont objects to the rich text using RichText->SetFont(int startPos, int endPos, ExcelFont* font) method.
  • Save the result file using Workbook->SaveToFile() method.
  • C++
#include "Spire.Xls.o.h";

using namespace Spire::Xls;

int main() {

	//Specify output file path and name
	std::wstring outputPath = L"Output\\";
	std::wstring outputFile = outputPath + L"ApplyMultipleFontstoCell.xlsx";

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

	//Get the first worksheet
	Worksheet* sheet = workbook->GetWorksheets()->Get(0);

	//Create a ExcelFont object and set its font style, color and size
	ExcelFont* font1 = workbook->CreateExcelFont();
	font1->SetKnownColor(ExcelColors::LightBlue);
	font1->SetIsBold(true);
	font1->SetSize(13);

	//Create another ExcelFont object and set its font style, color and size
	ExcelFont* font2 = workbook->CreateExcelFont();
	font2->SetKnownColor(ExcelColors::Red);
	font2->SetIsBold(true);
	font2->SetIsItalic(true);
	font2->SetFontName(L"Times New Roman");
	font2->SetSize(15);

	//Write a RichText string to cell B5
	RichText* richText = sheet->GetRange(L"B5")->GetRichText();
	richText->SetText(L"This document was created with Spire.XLS for C++.");

	//Apply two fonts to the text in the cell B5
	richText->SetFont(0, 29, font1);
	richText->SetFont(31, 48, font2);

	//Save to the result file
	workbook->SaveToFile(outputFile.c_str(), ExcelVersion::Version2013);
	workbook->Dispose();
}

C++: Apply Fonts to Excel Cells

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.

C++: Protect or Unprotect Word Documents

2023-04-03 01:15:08 Written by Koohji

Document security is particularly important when critical or private data is involved in a Word document. There are several security options in Word that you can use to protect your documents, including password protection, read-only mode, editing restrictions, and partial protection. On the contrary, when the protection is no longer required, you may need to unprotect a Word document to improve work efficiency.

In this article, you will learn how to protect or unprotect Word documents in C++ using Spire.Doc for C++.

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, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.Doc for C++ in a C++ Application

Password Protect a Word Document in C++

Encrypting a document with a password makes sure that only you and certain people can read or edit it. The following are the steps to password protect a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Encrypt the document with a password using Document->Eencrypt(LPCWSTR_S password) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    Document* document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample.docx");

    //Encrypt the document with a password
    document->Encrypt(L"open-psd");

    //Save the document to another Word file
    document->SaveToFile(L"Output/Encryption.docx", FileFormat::Docx2013);
    document->Close();
    delete document;
}

C++: Protect or Unprotect Word Documents

Restrict Editing of a Word Document in C++

If you want to grant people permission to read your document but restrict the types of modifications that someone can make, you can protect your document with a specific protection type and a permission password.

Protection Type Description
AllowOnlyComments Modification of comments in the document is allowed.
AllowOnlyFormFields The user can only enter data in the form fields in the document.
AllowOnlyReading The document is read-only.
AllowOnlyRevisions The user can only add revision marks to the document.
NoProtection The document is not protected.

The following are the steps to restrict editing of a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Protect the document by specifying the protection type and the permission password using Document->Protect(Spire::Doc::ProtectionType type, LPCWSTR_S password) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    Document* document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample.docx");

    //Protect the document by specifying the protection type and the password
    document->Protect(ProtectionType::AllowOnlyReading, L"permission-psd");

    //Save the document to another Word file
    document->SaveToFile(L"Output/RestrictEditing.docx", FileFormat::Docx2013);
    document->Close();
    delete document;
}

C++: Protect or Unprotect Word Documents

Protect Sections of a Word Document in C++

Word allows you to lock some sections of your Word document and leave the rest available for editing. The following are the steps to protect selected sections of a Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word document using Document->LoadFromFile() method.
  • Set the protection type to AllowOnlyFormFields using Document->Protect() method.
  • Unprotect a particular section by passing false as an argument to the Section->SetProtectForm() method. Other sections will continue to be protected.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    Document* document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample.docx");

    //Set the protection type as "AllowOnlyFormFields"
    document->Protect(ProtectionType::AllowOnlyFormFields, L"permission-psd");

    //Unprotect section 2
    document->GetSections()->GetItem(1)->SetProtectForm(false);

    //Save the document to another Word file
    document->SaveToFile(L"Output/ProtectSections.docx", FileFormat::Docx2013);
    document->Close();
    delete document;
}

C++: Protect or Unprotect Word Documents

Create Editable Regions in a Word Document in C++

Aside from making certain sections editable, you can create editable regions based on text ranges in order to narrow down the scope of changes that users are able to make. The following are the steps to create editable regions in a read-only Word document using Spire.Doc for C++.

  • Create a Document object.
  • Load a Word file using Document->LoadFromFile() method.
  • Set the protection type to AllowOnlyReading using Document->Protect() method.
  • Create a PermissionStart object and a PermissionEnd object.
  • Insert the PermissionStart object at the beginning of a paragraph using DocumentObjectCollection->Insert(int index, Spire::Doc::lDocumentObject *entity) method, which indicates the start of an editable region.
  • Add the PermissionEnd object at the end of a paragraph using DocumentObjectCollection->Add(Spire::Doc::lDocumentObject *entity) method, which indicates the end of an editable region.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    Document* document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\sample2.docx");

    //Set the protect type to AllowOnlyReading
    document->Protect(ProtectionType::AllowOnlyReading, L"permission-psd");

    //Create tags for permission start and end
    PermissionStart* start = new PermissionStart(document, L"regionOne");
    PermissionEnd* end = new PermissionEnd(document, L"regionOne");

    //Add the start and end tags to allow the selected paragraphs to be editable
    document->GetSections()->GetItem(0)->GetParagraphs()->GetItem(0)->GetChildObjects()->Insert(0, start);
    document->GetSections()->GetItem(0)->GetParagraphs()->GetItem(1)->GetChildObjects()->Add(end);

    //Save the document to another Word file
    document->SaveToFile(L"Output/SetEditableRegions.docx", FileFormat::Docx2013);
    document->Close();
    delete document;
}

C++: Protect or Unprotect Word Documents

Remove Editable Regions from a Word Document in C++

In order to remove the editable regions, you need to find the "PermissionStart" and "PermissionEnd" tags in the document and remove them. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document containing editable regions using Document->LoadFromFile() method.
  • Traverse through all the child objects in the document, and determine if a certain child object is an instance of PermissionStart class or PermissionEnd class. If yes, remove the child object from the paragraph using Paragraph->GetChildObjects()->Remove(Spire::Doc::IDocumentObject *entity) method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    Document* document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\SetEditableRegions.docx");

	//Find "PermissionStart" and "PermissionEnd" tags and remove them
	for (int i = 0; i < document->GetSections()->GetCount(); i++)
	{
		Section* section = document->GetSections()->GetItem(i);
		for (int j = 0; j < section->GetBody()->GetParagraphs()->GetCount(); j++)
		{
			Paragraph* para = section->GetBody()->GetParagraphs()->GetItem(j);
			for (int k = 0; k < para->GetChildObjects()->GetCount(); k++)
			{
				DocumentObject* obj = para->GetChildObjects()->GetItem(k);
				if (dynamic_cast<PermissionStart*>(obj) != nullptr || dynamic_cast<PermissionEnd*>(obj) != nullptr)
				{
					para->GetChildObjects()->Remove(obj);
				}
				else
				{
					k++;
				}
			}
		}
	}

    //Save the document to another Word file
    document->SaveToFile(L"Output/RemoveEditableRegions.docx", FileFormat::Docx2013);
    document->Close();
    delete document;
}

Remove Restrictions from a Word Document in C++

Spire.Doc for C++ allows you to remove editing restrictions without knowing the permission password. The following are the detailed steps.

  • Create a Document object.
  • Load a Word document containing editing restrictions using Document->LoadFromFile() method.
  • Set the protection type to NoProtection using Document->Protect() method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    Document* document = new Document();

    //Load a Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\RestrictEditing.docx");

    //Set the protect type to NoProtection
    document->Protect(ProtectionType::NoProtection);

    //Save the document to another Word file
    document->SaveToFile(L"Output/RemoveRestrictions.docx", FileFormat::Docx2013);
    document->Close();
    delete document;
}

Remove Password from a Password-Protected Word Document in C++

The password of an encrypted Word document can be removed if it is no longer needed. The following are the detailed steps.

  • Create a Document object.
  • Load a password-protected Word document using Document->LoadFromFile((LPCWSTR_S fileName, Spire::Doc::FileFormat fileFormat, LPCWSTR_S password) method.
  • Remove the password using Document->RemoveEncryption() method.
  • Save the document to another Word file using Document->SaveToFile() method.
  • C++
#include "Spire.Doc.o.h";

using namespace Spire::Doc;

int main() {

    //Create a Document object
    Document* document = new Document();

    //Load an encrypted Word file
    document->LoadFromFile(L"C:\\Users\\Administrator\\Desktop\\Encryption.docx", FileFormat::Docx, L"open-psd");

    //Remove the open password
    document->RemoveEncryption();

    //Save the document to another Word file
    document->SaveToFile(L"Output/RemovePassword.docx", FileFormat::Docx2013);
    document->Close();
    delete document;
}

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.

Excel and CSV (Comma-Separated Values) are two commonly used file formats for managing and storing tabular data in various industries. Excel organizes data in rows and columns and provides users with a wide range of advanced features for data manipulation, analysis and visualization, whereas CSV stores data in a plain text format that is lightweight and highly compatible with various applications. Converting Excel files to CSV format can be very helpful when users need to exchange or import Excel data in different programs. Conversely, users who require more advanced data analysis features, such as creating charts or applying formulas, may find it beneficial to convert CSV files to Excel format. In this article, we will demonstrate how to convert Excel to CSV or CSV to Excel in C++ using Spire.XLS for C++.

Install Spire.XLS for C++

There are two ways to integrate Spire.XLS for C++ into your application. One way is to install it through NuGet, and the other way is to download the package from our website and copy the libraries into your program. Installation via NuGet is simpler and more recommended. You can find more details by visiting the following link.

Integrate Spire.XLS for C++ in a C++ Application

Convert Excel to CSV in C++

Spire.XLS for C++ offers the XlsWorksheet->SaveToFile (LPCWSTR_S fileName, LPCWSTR_S separator, Spire::Common::Encoding* encoding) method to convert a worksheet in an Excel file to CSV. The detailed steps are as follows:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook->LoadFromFile() method.
  • Get a specific worksheet in the workbook by its index using Workbook->GetWorksheets()->Get(int index) method.
  • Save the worksheet to a CSV file using XlsWorksheet->SaveToFile (LPCWSTR_S fileName, LPCWSTR_S separator, Spire::Common::Encoding* encoding) method.
  • C++
#include "Spire.Xls.o.h";

using namespace Spire::Xls;

int main()
{
	//Initialize an instance of the Workbook class
	Workbook* workbook = new Workbook();
	//Load an Excel file
	workbook->LoadFromFile(L"Input.xlsx");

	//Get the first worksheet
	Worksheet* sheet = workbook->GetWorksheets()->Get(0);

	//Save the worksheet to a CSV file
	sheet->SaveToFile(L"ExcelToCsv.csv", L",", Encoding::GetUTF8());
	workbook->Dispose();
	delete workbook;
}

C++: Convert Excel to CSV or CSV to Excel

Convert Visible Data in Excel to CSV in C++

When converting an Excel worksheet to CSV using the above code, all data, including both visible and hidden data, will be saved to CSV. If you only want to save visible data in the worksheet to CSV, you can use the XlsWorksheet->SaveToFile (LPCWSTR_S fileName, LPCWSTR_S separator, bool retainHiddenData) method. The detailed steps are as follows:

  • Initialize an instance of the Workbook class.
  • Load an Excel file using Workbook->LoadFromFile() method.
  • Get a specific worksheet in the workbook by its index using Workbook->GetWorksheets()->Get(int index) method.
  • Save visible data in the worksheet to a CSV file using XlsWorksheet->SaveToFile (LPCWSTR_S fileName, LPCWSTR_S separator, bool retainHiddenData) method.
  • C++
#include "Spire.Xls.o.h";

using namespace Spire::Xls;

int main()
{
	//Initialize an instance of the Workbook class
	Workbook* workbook = new Workbook();
	//Load an Excel file
	workbook->LoadFromFile(L"Input.xlsx");

	//Get the first worksheet
	Worksheet* sheet = workbook->GetWorksheets()->Get(0);

	//Save visible data in the worksheet to a CSV file
	sheet->SaveToFile(L"ExcelToCsv1.csv", L",", false);
	workbook->Dispose();
	delete workbook;
}

C++: Convert Excel to CSV or CSV to Excel

Convert CSV to Excel in C++

To convert a CSV file to Excel, you need to load the CSV file using Workbook->LoadFromFile(LPCWSTR_S fileName, LPCWSTR_S separator) method, then use the Workbook->SaveToFile (LPCWSTR_S fileName, ExcelVersion version) method to save it to an Excel file. The detailed steps are as follows:

  • Initialize an instance of the Workbook class.
  • Load a CSV file with separator using Workbook->LoadFromFile(LPCWSTR_S fileName,LPCWSTR_S separator) method.
  • Get a specific worksheet in the file by its index using Workbook->GetWorksheets()->Get(int index) method.
  • Set ignore error option to ignore errors when saving numbers in a specific cell range as text using Worksheet->GetRange(LPCWSTR_S name)->SetIgnoreErrorOptions(IgnoreErrorType::NumberAsText) method.
  • Auto-fit column widths using Worksheet->GetAllocatedRange()->AutoFitColumns() method.
  • Save the CSV file to an Excel file using Workbook->SaveToFile (LPCWSTR_S fileName, ExcelVersion version) method.
  • C++
#include "Spire.Xls.o.h";

using namespace Spire::Xls;

int main()
{
	//Initialize an instance of the Workbook class
	Workbook* workbook = new Workbook();
	//Load a CSV file with separator
	workbook->LoadFromFile(L"ExcelToCSV.csv", L",");

	//Get the first worksheet
	Worksheet* sheet = workbook->GetWorksheets()->Get(0);

	//Set ignore error option to ignore errors when saving numbers in a specific cell range as text
	sheet->GetRange(L"C2:C11")->SetIgnoreErrorOptions(IgnoreErrorType::NumberAsText);

	//Auto-fit column widths
	sheet->GetAllocatedRange()->AutoFitColumns();

	//Save the file to an Excel XLSX file
	workbook->SaveToFile(L"CsvToExcel.xlsx", ExcelVersion::Version2013);
	workbook->Dispose();
	delete workbook;
}

C++: Convert Excel to CSV or CSV to Excel

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.

page 86

Coupon Code Copied!

Christmas Sale

Celebrate the season with exclusive savings

Save 10% Sitewide

Use Code:

View Campaign Details