Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

c# word document create title

  1. User

    c# word document create title

  2. Assistant

    To create a title in a Word document using C#, you need to specify the text you want to use as the title and add it to the document's header section. Here's some sample code to achieve this:

    using Microsoft.Office.Interop.Word;
    
    // create a Word application object
    Application wordApp = new Application();
    
    // create a new document
    Document doc = wordApp.Documents.Add();
    
    // get the header section of the document
    HeaderFooter header = doc.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary];
    
    // add the title text to the header
    Paragraph title = header.Range.Paragraphs.Add();
    title.Range.Text = "My Title";
    title.Range.Font.Name = "Arial";
    title.Range.Font.Size = 20;
    title.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
    
    // save the document
    doc.SaveAs("MyDoc.docx");
    

    In this example, we create a new Word application object and a new document. We then retrieve the header section of the document and add a new paragraph to it. We set the text of the paragraph to "My Title" and format it using the Arial font, size 20, and centered alignment. Finally, we save the document to a file called "MyDoc.docx".