【问题标题】:GetColumnName() LinqToExcel for csv file throw error The Microsoft Jet database engine could not find the object 'Sheet1$.txt'GetColumnName() LinqToExcel for csv file throw error Microsoft Jet 数据库引擎找不到对象“Sheet1$.txt”
【发布时间】:2016-04-21 10:34:55
【问题描述】:

我正在使用 linqToExcel dll 从读取 csv 文件并查询 csv 文件的数据。我还需要来自 csv 的列名(Header)。

当我尝试按照document mentioned 运行以下代码时

它会抛出如下错误消息:

Microsoft Jet 数据库引擎找不到对象“Sheet1$.txt”。确保对象存在并且正确拼写其名称和路径名。

我的代码如下:

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);

为了获得正确的工作表名称,我尝试使用 excelFile.GetWorksheetNames() 但它返回零记录。

注意:我使用的是 csv 文件,当我在 MS Excel 中打开相同的 csv 文件时,它会显示给我 学生作为工作表名称,即使我也尝试使用 sheet1。

【问题讨论】:

  • 确保您已安装 Microsoft Office Access。同时尝试将默认工作表名称从 sheet1 更改为其他名称
  • 你找到解决方案了吗?

标签: c# csv linq-to-excel


【解决方案1】:

这是我的解决方案:

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.");
}

【讨论】:

  • 我整天都在寻找这个!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多