c# - 在 C# 中读取 excel 2003(.xls)

标签 c# excel

我在读取 excel 2003 格式文件 (xls) 时遇到问题。

我正在使用带有 Windows 7 和 64 位处理器的 vs2008

如果我发送 excel 2007 格式文件 (.xlsx),下面的代码可以正常工作 我的系统中安装了 Office 2007。

这里我添加了引用

Microsoft Office 12.0 Object Library
Microsoft.Office.Tools.Excel.dll
Microsoft.Office.Tools.Excel.v9.0.dll
#region ExcelToDataTableChild

/// <summary>
/// Excel To DataTable for   attendance employee
/// </summary>
/// <param name="strfilelocation"></param>
/// <returns></returns>
public  DataTable ExcelToDataTableChild(string strfilelocation, string strfilename)
{
    OleDbConnection excelConn = new OleDbConnection();
    DataTable dtPatterns = new DataTable();
    string excelConnStr = string.Empty;
    try
    {
        string fileName = Path.GetExtension(@strfilelocation);
        DataSet ds = new DataSet();
        OleDbCommand excelCommand = new OleDbCommand(); OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter();
        
        #region Check FileExtension
        
        if (fileName.Equals(".xlsx"))
        {
            excelConnStr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strfilelocation + "; Extended Properties =Excel 8.0;";
        }
        if (fileName.Equals(".xls"))
        {
            excelConnStr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strfilelocation + "; Extended     Properties=Excel 8.0;";
        }
        
        #endregion
                

        excelConn = new OleDbConnection(excelConnStr);
        excelConn.Open();
        //excelCommand = new OleDbCommand("SELECT `Employee Name` as PATTERN FROM [sheet1$]", excelConn);
        excelCommand = new OleDbCommand("SELECT * FROM [sheet1$]", excelConn);
        excelDataAdapter.SelectCommand = excelCommand;
        excelDataAdapter.Fill(dtPatterns);
        dtPatterns.TableName = "EmpList";
        ds.Tables.Add(dtPatterns);
        dtPatterns.AcceptChanges();
    }
    catch (Exception ex)
    {
        WriteLogError(ex.Message);
    }
    finally
    {
        excelConn.Close();
    }
    return dtPatterns;
}

#endregion

上面的代码在我使用 Xp、VS 2008 的 excel 2003(.xls) 系统中运行良好。

代码工作正常,我可以毫无问题地读取 excel 2003 数据。

但相同的代码在 Windows 7、64 位处理器中失败

任何帮助我解决问题的方法都会很棒。

谢谢 王子

最佳答案

ACE 提供程序是 32 位的,您的应用程序应该以 32 位模式编译才能使用它。这是一个 thread这可能会有帮助。

关于c# - 在 C# 中读取 excel 2003(.xls),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3491764/

相关文章:

python - 如何获取不同单元格范围内的值?

excel - 如何在excel或VBA中搜索具有多个 "-"的项目?

vba - 连接备用列

c# - 如何优雅地保护方法免受未初始化接口(interface)参数的影响

c# - 如何创建返回二维数组的 UDF

arrays - VBA使用数组中的值创建Excel图表

excel - 列表中最常见的单词

c# - 我们可以在 C#.NET winform 中创建 4 个象限的 3D 图形吗?

c# - NET 5 在 Entity Framework Core 上添加迁移时出错

c# - ViewModel 中的构造函数