2010-03-10 84 views
0

我的程序通過使用PIA打開excel文件時遇到了問題。下面是我的示例代碼;有什麼建議麼?無法訪問c#中的excel文件

path = @"C:\\Test Template.xls"; 
wb = objExcel.Workbooks.Open(path, Missing.Value, Missing.Value , Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); 

我執行此代碼後,程序返回一個錯誤meesage「無法訪問Test Template.xls」。有人可以解釋這個錯誤的原因,我很困惑..

+0

是否有與該錯誤消息相關聯的信息嗎?拋出異常嗎? – Jay 2010-03-10 03:58:12

+0

你有沒有進入Missing.Value某處它指定了如何打開文件? – 2010-03-10 03:59:02

+0

System.Runtime.InteropServices.COMException未處理 HelpLink =「C:\\ Program Files \\ Microsoft Office \\ OFFICE11 \\ 1033 \\ xlmain11.chm」 這是它嗎?對不起,我還不熟悉你提到的那個 – 2010-03-10 06:31:31

回答

7

我敢肯定這個問題是在這裏:

path = @"C:\\Test Template.xls"; 

您應該使用「@」來表示的字符串是文字

path = @"C:\Test Template.xls"; 

或將反斜槓轉義爲「\\」。

path = "C:\\Test Template.xls"; 

不是兩個。

+0

+1我甚至沒有注意到雙反斜線!大聲笑 – 2010-03-10 04:20:41

+0

我做你的建議,但它給出了相同的結果, – 2010-03-10 06:28:31

0

你的語法不對.........

@ 「C:\測試\ templat.xls」 ......檢查這也使用系統

;

using System.IO;

using System.Reflection;

使用NUnit.Framework;

使用ExcelTools = Ms.Office;

using Excel = Microsoft.Office.Interop.Excel;

命名空間測試 {

public class ExcelSingle 
    { 
      public void ProcessWorkbook() 
      { 
        string file = @"C:\Users\Chris\Desktop\TestSheet.xls"; 
        Console.WriteLine(file); 

        Excel.Application excel = null; 
        Excel.Workbook wkb = null; 

        try 
        { 
          excel = new Excel.Application(); 

          wkb = ExcelTools.OfficeUtil.OpenBook(excel, file); 

          Excel.Worksheet sheet = wkb.Sheets["Data"] as Excel.Worksheet; 

          Excel.Range range = null; 

          if (sheet != null) 
            range = sheet.get_Range("A1", Missing.Value); 

          string A1 = String.Empty; 

          if(range != null) 
            A1 = range.Text.ToString(); 

          Console.WriteLine("A1 value: {0}", A1); 

        } 
        catch(Exception ex) 
        { 
          //if you need to handle stuff 
          Console.WriteLine(ex.Message); 
        } 
        finally 
        { 
          if (wkb != null) 
            ExcelTools.OfficeUtil.ReleaseRCM(wkb); 

          if (excel != null) 
            ExcelTools.OfficeUtil.ReleaseRCM(excel); 
        } 
      } 
    } 
+0

該代碼示例取自http://stackoverflow.com/a/657211/41153 – 2011-11-29 16:30:24