1

我必须创建一个服务来将数据从 excel 文件导入到 SQL Server 表中;整个系统属于我公司的一个客户,所以我必须使用 Visual Studio 2010。有些打开可能打开了这个文件,所以我决定将它复制到一个临时目录,然后解析这个副本。我以为我做到了,因为它在调试模式下正常工作:打开文件,读取所有行,最后将值写入数据库。我将它作为服务安装,但我不断收到相同的错误(翻译成英文):

System.Exception: System.Runtime.InteropServices.COMException (0x800A03EC): impossible access file "C:\[temp dir]\[file.xls]". Possible reasons are:

• file name or path file do not exists.
• file in use by another program.
• the name of the folder/worksheet you are trying to save corresponds to the name of an open folder/worksheet.
at Microsoft.Office.Interop.Excel.Workbooks.Open(String Filename, Object UpdateLinks, Object ReadOnly, Object Format, Object Password, Object WriteResPassword, Object IgnoreReadOnlyRecommended, Object Origin, Object Delimiter, Object Editable, Object Notify, Object Converter, Object AddToMru, Object Local, Object CorruptLoad)

该文件存在,我可以在文件夹中找到它,并且在服务尝试打开它时没有人使用它(我只是复制了它)。我不想保存它,我以只读模式打开它,这样我也可以排除第三点。我正在开发服务的机器与运行服务的机器相同,即 Windows 7 Ultimate、Service Pack 1。

我认为这可能是服务用户的问题,所以我尝试在 Visual Studio 中以调试模式启动服务,并使用相同的服务用户(管理员级别)登录到系统,它工作得非常好。然后我认为可能是时间问题,也许服务试图在系统没有释放文件的情况下“过早”打开文件,所以我添加了一个

System.Threading.Thread.Sleep(5000);

之前

xlApp = new Microsoft.Office.Interop.Excel.Application(); 

线,但没有任何改变。当然,每次我修改服务我都会停止它,将新文件复制到系统然后重新启动它。

代码是:

string fileName = "[file name].xlsm";
string sourcePath = @"[origin]";
string targetPath = @"[destination]";
string fileDest = "[destination file name].xls";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string targetFile = System.IO.Path.Combine(targetPath, fileDest);

try
{
    System.IO.File.Copy(sourceFile, targetFile, true);
}
catch (Exception myEx)
{
    throw new Exception(myEx.ToString());
}

xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.DisplayAlerts = false;
xlApp.Visible = false;
try
{
    wbk = xlApp.Workbooks.Open(targetFile, 0, true, Type.Missing, "[pwd]", "[pwd]", true, Type.Missing, Type.Missing, false, false, Type.Missing, true, Type.Missing, Type.Missing); [<- this is the problem, the exception is raised with these instruction]
    sheet = new Worksheet();
    range = null;
    sheet = wbk.Worksheets.get_Item(4);
    range = sheet.UsedRange;
    numColonne = range.Columns.Count;
    numRighe = range.Rows.Count;
}
catch (Exception myEx)
{
    throw new Exception(myEx.ToString());
}

我能做些什么来解决这个问题?谢谢你的帮助。

4

1 回答 1

2

我添加了这 2 个文件夹,C:\Windows\SysWOW64\config\systemprofile\Desktop(64 位)和 C:\Windows\System32\config\systemprofile\Desktop(32 位)。我在另一个论坛上找到了它们,我决定尝试一下;现在它可以工作了。不要问我为什么...

于 2019-01-21T14:39:37.920 回答