How to Convert TXT to Excel in C#
Converting TXT to Excel is a process of transforming plain text files (TXT) into structured spreadsheet files (like XLS or XLSX formats), making data easier to view, edit, and analyze. This conversion is valuable for handling and organizing data, especially in business, data analysis, and reporting contexts. This article will introduce how to programmatically convert a Text file (.txt) to Excel in C# using a free .NET library.
Free .NET Library for TXT to Excel Conversion
Free Spire.XLS for .NET is a free Excel library that supports a rich set of Excel processing feature (but with certain page limitation).
To begin with, we can install the library directly via Nuget. Or we can download it via below link and then manually add the dlls as reference.
Convert Text File to Excel in C#
To import data from a text file into Excel with C#, we need to do the following:
- Read the data in the text file line by line through the File.ReadAllLines(string path) method.
- Remove all leading and trailing white-space characters of each line through the Trim() method.
- Split the data by specified separator through the Split() method, and then store it into a list.
- Iterate through each row and column in the list.
- Fill the data into specified Excel cells through the Worksheet.Range[].Value property.
- Save the generated Excel file using the Workbook.SaveToFile() method.
C# code:
using Spire.Xls;
using System.IO;
using System.Linq;
namespace ExcelToTXT
{
class Program
{
static void Main(string[] args)
{
//Load a text file and read all lines in it
string[] lines = File.ReadAllLines("test.txt");
//Remove all leading and trailing white-space characters of each line, then split the data and store it in a list
var data = lines.Select(line => line.Trim().Split(' ').ToList()).ToList();
//Create an Excel workbook
Workbook workbook = new Workbook();
//Get the first worksheet
Worksheet sheet = workbook.Worksheets[0];
//Iterate through each row and column in the list
for (int rowNum = 0; rowNum < data.Count; rowNum++)
{
for (int colNum = 0; colNum < data[rowNum].Count; colNum++)
{
//Write the data into specified cells in Excel worksheet
sheet.Range[rowNum + 1, colNum + 1].Value = data[rowNum][colNum];
//Set the font of header line to bold
sheet.Range[1, colNum + 1].Style.Font.IsBold = true;
}
}
//Autofit column width
sheet.AllocatedRange.AutoFitColumns();
//Save as an Excel (xlsx/ xls) file
workbook.SaveToFile("TXTtoExcel.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Converting TXT to Excel brings simplicity, flexibility, and efficiency to data handling, making it a common task in data processing and business intelligence.
For more Excel file processing features provided by the free .NET Excel library, check the documentation: