locked
Convert txt data to xls data with saving in C:// path etc. RRS feed

  • Question

  • User-1507629948 posted

    Hello there, my english is bad, but i try to explain some points.

    point #1

    i have an idea to create a simple application, which will be converting some *txt files into *xls file

    point #2

    in *txt file some data's are wrong, it need to correct or delete, for example, if temperature in January couldn't be +2, then it is wrong/

    point #3

    then after converting into xls, it need to save in c://

    with best regards,

    Andrew S.

    Thursday, April 21, 2016 8:51 AM

Answers

  • User-2057865890 posted

    Hi Andrew,

    You could get the contents of a text file by using the static methods ReadAllText and ReadAllLines from the System.IO.File class.

    // Example #1
    // Read the file as one string.
    string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
    
    
    // Example #2
    // Read each line of the file into a string array. Each element
    // of the array is one line of the file.
    string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

    How to: Read From a Text File (C# Programming Guide)

    in *txt file some data's are wrong, it need to correct or delete

    Use string.Replace, returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

    string text = File.ReadAllText("test.txt");
    text = text.Replace("some text", "new value");

    then after converting into xls, it need to save in c://

    ClosedXML makes it easier for developers to create Excel files.

    To install ClosedXML, run the following command in the  Package Manager Console

    PM>  Install-Package ClosedXML

    Code snippets:

    string text = File.ReadAllText(@"C:\......\test.txt");
    text = text.Replace("some text", "new value");
    
    var workbook = new XLWorkbook();
    var worksheet = workbook.Worksheets.Add("Sample Sheet");
    worksheet.Cell("A1").Value = text;
    workbook.SaveAs(@"C:\......\text.xlsx");

    Best Regards,

    Chris

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 22, 2016 7:26 AM