Linq to Excel,从CSV文件中获取列名

时间:2018-03-01 09:59:54

标签: excel linq linq-to-excel

我需要使用LINQ to Excel获取CSV文件的列标题

我使用https://github.com/paulyoder/LinqToExcel

上指定的代码

这对.XLSX文件完全有效,但对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();

我也尝试过硬编码工作表名称并调用CSV sheet1

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

这打破并给我这个错误:

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

我仔细检查过它是正确的路径。

然后我尝试了:(它需要工作表名称与文件名相同 - 扩展名)

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

这给了我以下错误:

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.

我用谷歌搜索了那些不适用的错误。

1 个答案:

答案 0 :(得分:0)

我没有足够的时间弄清楚为什么我无法读取CSV列标题

对于那些有同样问题的人:

阅读第一行并列出字符串,这是我的方法:

    public List<string> ColumnNameGenerator(string FilePath)
    {

        string firstLine = "";
        using (StreamReader reader = new StreamReader(FilePath))
        {
            firstLine = reader.ReadLine() ?? "";
        }

        return firstLine.Split(',').ToList();
    }