我尝试将超链接插入到 ms word 文件中,并且超链接到另一个 word 文件中的书签。因为我已经知道包含书签的 word 文件的路径。所以我想将路径和书签名称(即:“path”+“#”+“bookmark_name”)组合为word文件中的超链接。因为在 ms word 中,超链接加上“#”符号并后跟书签名称将创建到书签的链接。
我的问题是,当我在代码中将“#”写为字符串时,运行我的代码。“#”符号不会正确写入word文件,它会变成一个条形符号“-”。我该如何应对?
这是代码:
这里的“#”符号将被更改,
string test_file_Path = created_folder + "\\test2.docx" + "#testsbookmark";
但MessageBox.Show(linkAddr.ToString());
它显示仍然正确。
public void AddContent(string filePath)
{
try
{
Object oMissing = System.Reflection.Missing.Value;
// Word Interface
Microsoft.Office.Interop.Word._Application WordApp = new Word.Application();
WordApp.Visible = true;
object filename = filePath;
Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
//
WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
//
WordApp.Selection.ParagraphFormat.LineSpacing = 15f;
//
//WordApp.Selection.TypeParagraph();
Microsoft.Office.Interop.Word.Paragraph para;
para = WordDoc.Content.Paragraphs.Add(ref oMissing);
//
para.Range.Text = "This is paragraph 1";
//para.Range.Font.Bold = 2;
//para.Range.Font.Color = WdColor.wdColorRed;
//para.Range.Font.Italic = 2;
para.Range.InsertParagraphAfter();
para.Range.Text = "This is paragraph 2";
para.Range.InsertParagraphAfter();
//insert Hyperlink
Microsoft.Office.Interop.Word.Selection mySelection = WordApp.ActiveWindow.Selection;
mySelection.Start = 9999;
mySelection.End = 9999;
Microsoft.Office.Interop.Word.Range myRange = mySelection.Range;
Microsoft.Office.Interop.Word.Hyperlinks myLinks = WordDoc.Hyperlinks;
string test_file_Path = created_folder + "\\test2.docx" + "#testsbookmark";
object linkAddr = test_file_Path;
MessageBox.Show(linkAddr.ToString());
Microsoft.Office.Interop.Word.Hyperlink myLink = myLinks.Add(myRange, ref linkAddr,
ref oMissing);
WordApp.ActiveWindow.Selection.InsertAfter("\n");
//
WordDoc.Paragraphs.Last.Range.Text = "Created:" + DateTime.Now.ToString();
WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
//
WordDoc.Save();
WordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
WordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
//return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
//return false;
}
}