How to arrange text data in columns when writing to a TXT file using C#?

To write data to a TXT text file in column format, you can use the StreamWriter class. Here is an example code:

using System;
using System.IO;

class Program
{
    static void Main()
    {
        string filePath = "data.txt";
        
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            writer.WriteLine("Column1\tColumn2\tColumn3"); // 写入表头
            
            // 写入数据
            writer.WriteLine("Data1\tData2\tData3");
            writer.WriteLine("Data4\tData5\tData6");
            writer.WriteLine("Data7\tData8\tData9");
        }
        
        Console.WriteLine("Data has been written to " + filePath);
    }
}

In the example above, we created a TXT text file named data.txt and used the StreamWriter class to write data in columns. Tabs were used to separate the columns when writing the data.

After running the program, the data will be written to the data.txt file in the following format:

Column1 Column2 Column3
Data1   Data2   Data3
Data4   Data5   Data6
Data7   Data8   Data9

Please modify the data and file paths according to your actual needs.

bannerAds