日期:2014-05-18  浏览次数:20428 次

郁闷啊~~~读取Excel文件的问题!!!
读取客户端的一个excel文件代码如下:
public   static   DataSet   GetDataSet(string   FilePath)
{
OleDbConnection   objConn=null;
DataSet   data=new   DataSet();
//strConn   =   "Provider=Microsoft.Jet.OLEDB.4.0; "   +   "Data   Source=Server.MapPath(@ "excelFilePath ");Extended   Properties=Excel   8.0; ";


string   strConn=   "Provider=Microsoft.Jet.OleDb.4.0;data   source=   "   +   FilePath   +   ";Extended   Properties= 'Excel   8.0;HDR=Yes;IMEX=1 ' ";
try
{
objConn=new   OleDbConnection(strConn);
objConn.Open();
string   strSql=   "Select   *   From   [ "+GetExcelWorkSheet(FilePath)+ "$] ";
OleDbCommand   objCmd=new   OleDbCommand(strSql,   objConn);
OleDbDataAdapter   sqlada=new   OleDbDataAdapter();
sqlada.SelectCommand=objCmd;
sqlada.Fill(data, "ExlDt ");
}
catch(Exception   Exp)
{
throw   Exp;
}
finally
{
objConn.Close();
objConn.Dispose();
}

return   data;
}

private   static   string   GetExcelWorkSheet(string   FilePath)
{
//   '返回给定路径   Excel   文件的   workSheet   名字
Excel.ApplicationClass   myExcel   =new   Excel.ApplicationClass();
string   xlName;
// '得到worksheet名字
myExcel.Workbooks.Open(FilePath,System.Reflection.Missing.Value,false,System.Reflection.Missing.Value,null,null,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value,System.Reflection.Missing.Value);
Excel.Sheets   mySh   =myExcel.Sheets;
Excel.Worksheet   myWs=(Excel.Worksheet)mySh.get_Item(1);
xlName   =   myWs.Name;
// '关闭excel处理
myExcel.Workbooks.Close();
myExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject   (myExcel);
System.Runtime.InteropServices.Marshal.ReleaseComObject   (mySh);
System.Runtime.InteropServices.Marshal.ReleaseComObject   (myWs);
mySh   =null;
myWs   =   null;
myExcel   =   null;
GC.Collect();
// '返回名字字符串
return   xlName;
}

但是总是报在objConn.Open();出错
The   Microsoft   Jet   database   engine   cannot   open   the   file   'C:\Documents   and   Settings\qinpl\Desktop\SLIMDMSOto0103_001.xls '.     It   is   already   opened   exclusively   by   another   user,   or   you   need   permission   to   view   its   data.

各位高手帮忙看看吧

------解决方案--------------------
确保你的excel文件 没有被 其它程序打开 比如excel程序本身

重新启动你的电脑 运行你的程序.
添加函数
/// <summary>
/// 强行终止指定名称的进程
/// </summary>
/// <param name= "ProcessName "> 指定进程名称 </param>
public void KillProcess(string ProcessName)
{
try
{
System.Diagnostics.Process[] process;
process=System.Diagnostics.Process.GetProcessesByName(ProcessName.Trim());