2

I am using linqToExcel dll from to read a csv file and query the csv file the data . I also neeed the names of columns (Header ) from csv .

when i try to run the following code as per the document mentioned

its throw an error message as follow :

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

my code is as follow :

string pathToExcelFile = ""
        + @"c:\users\rahul\documents\visual studio 2013\Projects\WebApplication1\WebApplication1\csv\student.csv";

            string sheetName = "student";

            var excelFile = new ExcelQueryFactory(pathToExcelFile);

            //get all sheet names 
            var sheetNames = excelFile.GetWorksheetNames();

            //get column name from csv 
            var columnNames = excelFile.GetColumnNames(sheetName);

To get the correct sheet name i tried to use excelFile.GetWorksheetNames() but its return zero records.

Note: I am using csv file and when i open same csv file in MS Excel its shows me student as Sheet Name even i tried with sheet1 as well.

rahularyansharma
  • 11,156
  • 18
  • 79
  • 135

1 Answers1

4

Here's my solution:

IEnumerable<string> columnNames;
var workSheetName = excel.GetWorksheetNames().FirstOrDefault();
if (string.IsNullOrEmpty(workSheetName))
{
    // CSV files do not have worksheet names
    var worksheet = excel.Worksheet();
    if (worksheet == null)
    {
        throw new ApplicationException("Unable to extract data. The file contains no data");
    }
    var row = worksheet.FirstOrDefault();
    if (row == null)
    {
        throw new ApplicationException("Unable to extract data. The file contains no rows.");
    }
    columnNames = row.ColumnNames;

}
else
{
    columnNames = excel.GetColumnNames(workSheetName);
}

if (columnNames == null || !columnNames.Any())
{
    throw new ApplicationException("Unable to extract column information.");
}
RoastBeast
  • 1,059
  • 2
  • 22
  • 38
tymtam
  • 31,798
  • 8
  • 86
  • 126