excellinqlinq-to-excel

Linq to Excel, get column names from CSV file


I need to get the column headers of CSV files with LINQ to Excel

I use the code specified on https://github.com/paulyoder/LinqToExcel

This works perefectly for .XLSX files but not for CSV

           //Select File

        var book = new LinqToExcel.ExcelQueryFactory(link + @"\" + fileName);

           //Select firtworkbook
        var query = (from row in book.Worksheet(0) select row).ToList();
        var workSheetName = book.GetWorksheetNames();
        var columnNames = (from row in book.GetColumnNames(workSheetName.FirstOrDefault()) select row).ToList();

I also tried hardcoding the sheet name and calling the CSV sheet1

        var columnNames = (from row in book.GetColumnNames("Sheet1") select row).ToList();

This breaks and gives me this error:

 Message = "'54733658.csv' is not a valid worksheet name in file...

I double checked it is the correct path.

I then tried:(It takes worksheet name which is the same as file name - extention)

        string extension = System.IO.Path.GetExtension(fileName);
        string result = fileName.Substring(0, fileName.Length - extension.Length);
        var colNames = book.GetColumnNames(result, "A1:F1").ToList();

This gives me the following error:

The Microsoft Jet database engine could not find the object '02119249$A1_Z1.txt'.  Make sure the object exists and that you spell its name and the path name correctly.

I googled that error those results are not applicable.


Solution

  • I don't have enough time to figure out why I cant read the CSV column headers

    For those of you who have the same issue:

    Read the first line and make a list of strings, here is my method:

        public List<string> ColumnNameGenerator(string FilePath)
        {
    
            string firstLine = "";
            using (StreamReader reader = new StreamReader(FilePath))
            {
                firstLine = reader.ReadLine() ?? "";
            }
    
            return firstLine.Split(',').ToList();
        }