【发布时间】:2019-09-27 01:21:10
【问题描述】:
我正在尝试通过以下代码打开 excel,但在线出现错误:
string excelFile = @"D:\Hello.xlsx";
Workbook xlWorkbook = (Workbook)xlApp.Workbooks.Open(excelFile);
Excel 版本:MS Office Professional plus 2016
错误: ExcelHighlight.exe 中出现“System.Runtime.InteropServices.COMException”类型的未处理异常 附加信息:抱歉,我们找不到 D:\Hello.xlsx。它是否可能被移动、重命名或删除?
代码:
try
{
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
{
}
}
【问题讨论】:
-
请附上您的 Windows 资源管理器的屏幕截图,显示位于
D:\文件夹中的Hello.xlsx文件。 -
更新了 Windows 资源管理器的屏幕截图和问题顶部的 visualstudio 错误。
-
是的,我检查它是“D:\Hello.xlsx”。我的系统窗口是“Windows 10”
-
您必须将 Explorer 置于程序员模式。使用控制面板>文件资源管理器选项>查看选项卡并取消选中“隐藏已知文件类型的扩展名”复选框。现在你可以看到一个基本的错误,比如这个文件实际上被命名为 Hello.xls
标签: c# excel office-interop