简体   繁体   English

如何使用C#和OneNote Interop写入OneNote 2013页面

[英]How To Write To A OneNote 2013 Page Using C# and The OneNote Interop

I have seen many articles about this but all of them are either incomplete or do not answer my question. 我见过很多关于此的文章,但所有文章都不完整或者没有回答我的问题。 Using C# and the OneNote Interop, I would like to simply write text to an existing OneNote 2013 Page. 使用C#和OneNote Interop,我想简单地将文本写入现有的OneNote 2013页面。 Currently I have a OneNote Notebook, with a Section titled "Sample_Section " and a Page called "MyPage" . 目前我有一个OneNote笔记本,标题为"Sample_Section ”的部分和名为"MyPage"的页面。

I need to be able to use C# code to write text to this Page, but I cannot figure out how or find any resources to do so. 我需要能够使用C#代码将文本写入此页面,但我无法弄清楚如何或找到任何资源来执行此操作。 I have looked at all of the code examples on the web and none answer this simple question or are able to do this. 我已经查看了网络上的所有代码示例,没有人回答这个简单的问题,或者能够做到这一点。 Also many of the code examples are outdated and break when attempting to run them. 此外,许多代码示例在尝试运行它们时已过时并中断。

I used the Microsoft code sample that shows how to change the name of a Section but I cannot find any code to write text to a Page . 我使用Microsoft代码示例演示如何更改Section的名称,但我找不到任何代码来将文本写入Page There is no simple way to do this that I can see. 我可以看到没有简单的方法可以做到这一点。 I have taken a lot of time to research this and view the different examples online but none are able to help. 我花了很多时间研究这个并在线查看不同的例子,但没有人能够提供帮助。

I have already viewed the MSDN articles on the OneNote Interop as well. 我已经在OneNote Interop上查看了MSDN文章。 I vaguely understand how the OneNote Interop works through XML but any extra help understanding that would also be appreciated. 我模糊地理解OneNote Interop如何通过XML但任何额外的帮助理解也会受到赞赏。 Most importantly I would really appreciate a code example that demonstrates how to write text to a OneNote 2013 Notebook Page. 最重要的是,我非常感谢一个代码示例,该示例演示了如何将文本写入OneNote 2013 Notebook页面。

I have tried using this Stack Overflow answer: Creating new One Note 2010 page from C# 我尝试使用此Stack Overflow答案: 从C#创建新的One Note 2010页面

However, there are 2 things about this solution that do not answer my question: 但是,这个解决方案有两件事没有回答我的问题:

1) The marked solution shows how to create a new page, not how to write text to it or how to populate the page with any information. 1)标记的解决方案显示了如何创建新页面,而不是如何向其中写入文本或如何使用任何信息填充页面。

2) When I try to run the code that is marked as the solution, I get an error at the following line: 2)当我尝试运行标记为解决方案的代码时,我在以下行收到错误:

var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();
return node.Attribute("ID").Value;

The reason being that the value of "node" is null, any help would be greatly appreciated. 原因是“节点”的值为null,任何帮助都将非常感激。

I asked the same question on MSDN forums and was given this great answer. 我在MSDN论坛上问了同样的问题并得到了这个很好的答案。 Below is a nice, clean example of how to write to OneNote using C# and the OneNote interop. 下面是一个很好的,干净的示例,说明如何使用C#和OneNote互操作写入OneNote。 I hope that this can help people in the future. 我希望这可以在将来帮助人们。

    static Application onenoteApp = new Application();
    static XNamespace ns = null;

    static void Main(string[] args)
    {
        GetNamespace();
        string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "MyNotebook");
        string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "Sample_Section");
        string firstPageId = GetObjectId(sectionId, OneNote.HierarchyScope.hsPages, "MyPage");
        GetPageContent(firstPageId);
        Console.Read();
    }
    static void GetNamespace()
    {
        string xml;

        onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out xml);
        var doc = XDocument.Parse(xml);
        ns = doc.Root.Name.Namespace;
    }

    static string GetObjectId(string parentId, OneNote.HierarchyScope scope, string objectName)
    {
        string xml;
        onenoteApp.GetHierarchy(parentId, scope, out xml);

        var doc = XDocument.Parse(xml);
        var nodeName = "";

        switch (scope)
        {
            case (OneNote.HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
            case (OneNote.HierarchyScope.hsPages): nodeName = "Page"; break;
            case (OneNote.HierarchyScope.hsSections): nodeName = "Section"; break;
            default:
                return null;
        }

        var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();

        return node.Attribute("ID").Value;
    }
    static string GetPageContent(string pageId)
    {
        string xml;
        onenoteApp.GetPageContent(pageId, out xml, OneNote.PageInfo.piAll);
        var doc = XDocument.Parse(xml);
        var outLine = doc.Descendants(ns + "Outline").First();
        var content = outLine.Descendants(ns + "T").First();
        string contentVal = content.Value;
        content.Value = "modified";
        onenoteApp.UpdatePageContent(doc.ToString());
        return null;
    }

This is just what I've gleaned from reading examples on the web (of course, you've already read all of those ) and peeking into the way OneNote stores its data in XML using ONOMspy ( http://blogs.msdn.com/b/johnguin/archive/2011/07/28/onenote-spy-omspy-for-onenote-2010.aspx ). 这正是我通过阅读网络上的示例(当然,您已经阅读了所有这些内容 )和窥探OneNote使用ONOMspy将数据存储在XML中的方式( http://blogs.msdn.com /b/johnguin/archive/2011/07/28/onenote-spy-omspy-for-onenote-2010.aspx )。

If you want to work with OneNote content, you'll need a basic understanding of XML. 如果您想使用OneNote内容,则需要对XML有基本的了解。 Writing text to a OneNote page involves creating an outline element, whose content will be contained in OEChildren elements. 将文本写入OneNote页面涉及创建大纲元素,其内容将包含在OEChildren元素中。 Within an OEChildren element, you can have many other child elements representing outline content. OEChildren元素中,您可以使用许多其他子元素来表示大纲内容。 These can be of type OE or HTMLBlock , if I'm reading the schema correctly. 如果我正确读取架构,它们可以是OEHTMLBlock类型。 Personally, I've only ever used OE , and in this case, you'll have an OE element containing a T (text) element. 就个人而言,我只使用过OE ,在这种情况下,你将拥有一个包含T (文本)元素的OE元素。 The following code will create an outline XElement and add text to it: 以下代码将创建一个大纲XElement并向其添加文本:

// Get info from OneNote
string xml;
onApp.GetHierarchy(null, OneNote.HierarchyScope.hsSections, out xml);
XDocument doc = XDocument.Parse(xml);
XNamespace ns = doc.Root.Name.Namespace;

// Assuming you have a notebook called "Test"
XElement notebook = doc.Root.Elements(ns + "Notebook").Where(x => x.Attribute("name").Value == "Test").FirstOrDefault();
if (notebook == null)
{
    Console.WriteLine("Did not find notebook titled 'Test'.  Aborting.");
    return;
}

// If there is a section, just use the first one we encounter
XElement section;
if (notebook.Elements(ns + "Section").Any())
{
    section = notebook.Elements(ns + "Section").FirstOrDefault();
}
else
{
    Console.WriteLine("No sections found.  Aborting");
    return;
}

// Create a page
string newPageID;
onApp.CreateNewPage(section.Attribute("ID").Value, out newPageID);

// Create the page element using the ID of the new page OneNote just created
XElement newPage = new XElement(ns + "Page");
newPage.SetAttributeValue("ID", newPageID);

// Add a title just for grins
newPage.Add(new XElement(ns + "Title",
    new XElement(ns + "OE",
        new XElement(ns + "T",
            new XCData("Test Page")))));

// Add an outline and text content
newPage.Add(new XElement(ns + "Outline",
    new XElement(ns + "OEChildren",
        new XElement(ns + "OE",
            new XElement(ns + "T",
                new XCData("Here is some new sample text."))))));

// Now update the page content
onApp.UpdatePageContent(newPage.ToString());

Here's what the actual XML you're sending to OneNote looks like: 以下是您发送给OneNote的实际XML的样子:

<Page ID="{20A13151-AD1C-4944-A3D3-772025BB8084}{1}{A1954187212743991351891701718491104445838501}" xmlns="http://schemas.microsoft.com/office/onenote/2013/onenote">
  <Title>
    <OE>
      <T><![CDATA[Test Page]]></T>
    </OE>
  </Title>
  <Outline>
    <OEChildren>
      <OE>
        <T><![CDATA[Here is some new sample text.]]></T>
      </OE>
    </OEChildren>
  </Outline>
</Page>

Hope that helps get you started! 希望有助于您入门!

Given task can be easily solved using Aspose.Note . 使用Aspose.Note可以轻松解决给定任务。 Following code creates a new Document and adds text to its title: 以下代码创建一个新文档并在其标题中添加文本:

var doc = new Document();
var page = new Page(doc);
page.Title = new Title(doc)
{
    TitleText = new RichText(doc)
                    {
                        Text = "Title text.",
                        DefaultStyle = TextStyle.DefaultMsOneNoteTitleTextStyle
                    },
    TitleDate = new RichText(doc)
                    {
                        Text = new DateTime(2011, 11, 11).ToString("D", CultureInfo.InvariantCulture),
                        DefaultStyle = TextStyle.DefaultMsOneNoteTitleDateStyle
                    },
    TitleTime = new RichText(doc)
                    {
                        Text = "12:34",
                        DefaultStyle = TextStyle.DefaultMsOneNoteTitleTimeStyle
                    }
};
page.AppendChild(outline);
doc.AppendChild(page);
doc.Save("output.one")

If you're using C#, Check out the newer OneNote REST API at http://dev.onenote.com . 如果您使用的是C#,请在http://dev.onenote.com上查看较新的OneNote REST API。 It already supports creating a new page and has a beta API to patch and add content to an existing page. 它已经支持创建新页面,并且具有用于修补和向现有页面添加内容的beta API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM