Adding Text to an Excel document using C# and .NET

In today's world of data processing, programming and automating many routine tasks are becoming a necessity. One such solution is SautinSoft.Excel library. In this article, we will look at how to add text to an Excel document using C# and .NET and why such a function is needed.

Adding text to an Excel document can be used in a variety of scenarios:
  • Report Automation. Developers can create applications that automatically generate reports by filling them with data from databases or other sources.
  • Data processing. When working with large amounts of information, the ability to programmatically add text to tables can speed up the data processing process and minimize the likelihood of errors.
  • Dynamic information update. It is often necessary to update Excel data in response to changes in the system. Automated scripts can minimize the time required for manual data entry.
  • Generating custom documents. Creating personalized documents for clients, such as invoices or contracts, can be simplified by automation.

Step-by-step guide:

  1. Add SautinSoft.Excel from Nuget.
  2. Create a new Excel document and add an empty worksheet.
  3. Insert the content with different formatting.
  4. Save the Excel document.

Complete code

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SautinSoft.Excel;
using SkiaSharp;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free key here:   
            // https://sautinsoft.com/start-for-free/

            AllTypesOfText();
        }

        /// <summary>
        /// Using various methods of inserting text into cells.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/using-text-xlsx-net-csharp-vb.php
        /// </remarks>
        static void AllTypesOfText()
        {
            string outFile = @"..\..\..\Result.xlsx";
            // The file format is detected automatically from the file extension: ".xlsx".
            ExcelDocument excel = new ExcelDocument();
            
            // Add an empty worksheet to the file.
            excel.Worksheets.Add("Page 1");
            var worksheet = excel.Worksheets["Page 1"];


            // This is a regular string.
            worksheet.Cells["A1"].Value = "Hello, World!";
            

            // This is a string with a calculation in C#.
            worksheet.Cells["A2"].Value = $"2+2*2 equals {2 + 2 * 2}";
            worksheet.Cells["B2"].Value = 2+2*2;

            
            // This is a string created using StringBuilder.
            var stringBuilder = new StringBuilder("Hello");
            stringBuilder.Append(" World");
            stringBuilder.Insert(5, ",");
            worksheet.Cells["A3"].Value = stringBuilder;


            // This is a RichText string with varied formatting.
            var wholeString = new RichText();
            var part1 = new RichTextString("Hello", new RichTextFormat() { Italic = true, FontColor = SKColors.Blue });
            var part2 = new RichTextString(", ", new RichTextFormat() { FontColor = SKColors.Red });
            var part3 = new RichTextString("World!", new RichTextFormat() { Bold = true, FontSize = 18, FontColor = SKColors.Green });

            wholeString.Add(part1); wholeString.Add(part2); wholeString.Add(part3);
            worksheet.Cells["A4"].Value = wholeString;

            // Expand the column to make it look attractive
            worksheet.Columns["A"].AutoFit();

            // Saving the excel document.
            excel.Save(outFile);

            // Important for Linux: Install MS Fonts
            // sudo apt install ttf-mscorefonts-installer -y

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Text
Imports SautinSoft.Excel
Imports SkiaSharp

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Get your free key here:   
			' https://sautinsoft.com/start-for-free/

			AllTypesOfText()
		End Sub

		''' <summary>
		''' Using various methods of inserting text into cells.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/using-text-xlsx-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub AllTypesOfText()
			Dim outFile As String = "..\..\..\Result.xlsx"
			' The file format is detected automatically from the file extension: ".xlsx".
			Dim excel As New ExcelDocument()

			' Add an empty worksheet to the file.
			excel.Worksheets.Add("Page 1")
			Dim worksheet = excel.Worksheets("Page 1")


			' This is a regular string.
			worksheet.Cells("A1").Value = "Hello, World!"


			' This is a string with a calculation in C#.
			worksheet.Cells("A2").Value = $"2+2*2 equals {2 + 2 * 2}"
			worksheet.Cells("B2").Value = 2+2*2


			' This is a string created using StringBuilder.
			Dim stringBuilder As New StringBuilder("Hello")
			stringBuilder.Append(" World")
			stringBuilder.Insert(5, ",")
			worksheet.Cells("A3").Value = stringBuilder


			' This is a RichText string with varied formatting.
			Dim wholeString = New RichText()
			Dim part1 = New RichTextString("Hello", New RichTextFormat() With {
				.Italic = True,
				.FontColor = SKColors.Blue
			})
			Dim part2 = New RichTextString(", ", New RichTextFormat() With {.FontColor = SKColors.Red})
			Dim part3 = New RichTextString("World!", New RichTextFormat() With {
				.Bold = True,
				.FontSize = 18,
				.FontColor = SKColors.Green
			})

			wholeString.Add(part1)
			wholeString.Add(part2)
			wholeString.Add(part3)
			worksheet.Cells("A4").Value = wholeString

			' Expand the column to make it look attractive
			worksheet.Columns("A").AutoFit()

			' Saving the excel document.
			excel.Save(outFile)

			' Important for Linux: Install MS Fonts
			' sudo apt install ttf-mscorefonts-installer -y

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.