c# word paragraph
c# word paragraph
Here is my opinion:
First see the code below:
//Create Empty
var wordApp = new Word.Application();
string template = "Normal.dot";//這句好像沒用??
Word.Document doc = wordApp.Documents.Add();
//set text
Word.Range range = doc.Paragraphs[1].Range;
range.Text = "test text";
//Save
object savedPath = @"yourSavePath\TestWord.docx";
doc.SaveAs(ref savedPath);
wordApp.Application.Quit();
By the common sense of C#, first I think the key is doc.Paragraphs[1] , I guess Paragraphs[] may like a List, and you can add many Paragraph to Paragraphs[], and set the text in Paragraphs[i], i is 1,2,3,4, ...
but then I find many Exception, for example, use following code in the //Set Text section
for (int i = 1; i < 5; i++)
{
Word.Range range = doc.Paragraphs[i].Range;
range.Text = String.Format("this is the {0} paragraph text", i);
doc.Paragraphs.Add(range);
}
then I found all the behaviour are all strange, that mean I'm in the wrong way.
FInally I preliminarily got the hang of it, following code works:
for (int i = 0; i < 5; i++)
{
var para = doc.Paragraphs.Add();
para.Range.Text = String.Format("this is the {0} paragraph text", i);
para.Range.InsertParagraphAfter();
}
I feel it is something like Buffer, or the iterator in some StreamReader
the Add is like GetNext or New A Buffer And Read,
and the InsertParagraph is like Save or Insert Or WriteBuffer
I got the usage from this article, this is great and amazing , workable
http://csharphelper.com/blog/2014/11/create-a-word-document-in-c/
and the MSDN Official Tutorial
Notice the left side list in the MSDN can view more article
Walkthrough: Office Programming (C# and Visual Basic)
Work with documents
https://docs.microsoft.com/en-us/visualstudio/vsto/working-with-documents?view=vs-2017
Work with text in documents
https://docs.microsoft.com/en-us/visualstudio/vsto/working-with-text-in-documents?view=vs-2017
How to: Programmatically format text in documents
Inserting an Image and Scaling
How to merge cells of a table created in MS Word using C#.NET?
inserting a picture into word and changing the position
Set Image position Absolute position (text through) in MS word using VB.Net code