我在读取 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/