簡體   English   中英

無法使用 C# 服務打開 xls 文件

[英]Cannot open xls file with C# service

我必須創建一個服務來將數據從 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());
}

我能做些什么來解決這個問題? 謝謝你的幫助。

我添加了這 2 個文件夾,C:\\Windows\\SysWOW64\\config\\systemprofile\\Desktop(64 位)和 C:\\Windows\\System32\\config\\systemprofile\\Desktop(32 位)。 我在另一個論壇上找到了它們,我決定嘗試一下; 現在它起作用了。 不要問我為什么...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM