2010-03-10 82 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