我正在尝试通过下面的代码打开excel,但是在网上出现错误:
字符串excelFile = @“D:\ Hello.xlsx”; 工作簿xlWorkbook =(工作簿)xlApp.Workbooks.Open(excelFile);
Excel版本:MS Office Professional plus 2016
错误: ExcelHighlight.exe中发生了类型为'System.Runtime.InteropServices.COMException'的未处理异常 附加信息:对不起,我们找不到D:\ Hello.xlsx。是否有可能被移动,重命名或删除?
代码:
尝试
{
string FullPath = System.IO.Path.GetFullPath("Words.xml");
string[] arr = XDocument.Load(FullPath).Descendants("Highlight").Descendants().Select(x => x.ToString()).ToArray();
Application xlApp = new Application();
string excelFile = @"D:\Hello.xlsx";
Workbook xlWorkbook = (Workbook)xlApp.Workbooks.Open(excelFile);
Sheets sheet = xlWorkbook.Worksheets;
string str;
int rCnt = 0;
int cCnt = 0;
Worksheet xlWorkSheet4;
Range range;
xlWorkSheet4 = (Worksheet)sheet.get_Item(1);
Range last3 = xlWorkSheet4.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
range = xlWorkSheet4.get_Range("A1", last3);
for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
{
if (range.Cells[rCnt, cCnt].Value2 is string)
{
str = (string)(range.Cells[rCnt, cCnt] as Range).Value2;
if (str == null)
{
Console.WriteLine("null");
}
else
{
str.Replace("\\", "");
string[] words = str.Split(' ');
foreach (string arrs in arr)
{
foreach (string word in words)
{
if (word == arrs)
{
var cell = (range.Cells[rCnt, cCnt] as Range);
cell.Font.Bold = 1;
cell.Font.Color = ColorTranslator.ToOle(Color.Red);
}
}
}
}
}
else
{
Console.WriteLine("not string");
}
}
}
}
finally
{
}
}
答案 0 :(得分:0)
尝试将代码中指定的字符串传递给Process.Start
方法。如果仍然找不到文件,则需要检查文件扩展名,并从开头删除@
符号(删除逐字字符串),并改用以下路径:
string excelFile = "D:\\Hello.xlsx";