我的程序有问题,通过使用PIA打开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);
执行此代码后,程序返回错误消息“无法访问Test Template.xls”。有人可以解释这个错误的原因,我很困惑..
答案 0 :(得分:7)
我很确定问题就在这里:
path = @"C:\\Test Template.xls";
你应该使用“@”来表示字符串是字面的
path = @"C:\Test Template.xls";
或以“\\”转义反斜杠。
path = "C:\\Test Template.xls";
不是两个。
答案 1 :(得分:0)
你的语法错误.........
@“C:\ Test \ templat.xls”....也检查这个
使用System;
使用System.IO;
使用System.Reflection;
使用NUnit.Framework;
使用ExcelTools = Ms.Office;
使用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);
}
}
}