C implements the method of automatically creating Word documents through templates
- 2020-11-03 22:33:59
- OfStack
The example in this article shows how C# is a very useful technique for implementing the method of automatically creating Word documents through templates. Share to everybody for everybody reference. Specific implementation methods are as follows:
Introduction: Some time ago, I had a project to use c# to generate a calculation report in Word format. I found a lot of contents through the Internet, but they were all very messy. So I decided to summarize the specific steps, so that I could communicate better and solve similar problems quickly in the future!
Concrete examples are given to demonstrate the specific steps:
Step 1: Make a template
1. Create a new document and set its content.
2. Insert a bookmark in the corresponding position; Position the mouse over the position where you want to insert a bookmark, and click "Insert"
>
"Bookmark", pop-up dialog box, enter book signature, click "Add" button.
3. Save the template and name it "Template 1.dot" or "Template 1.ES17en"
Step 2, set the reference in the project
1. Right click "References" in the project directory in Solution Explorer, and select "Add References" to open the "Add References" dialog box
2. In the Add References dialog box, select COM
>
"Microsoft Word 11.0 Object Library", click "OK" button
3. The same operation to open the "add reference" dialog box, select "browse", find "Microsoft. Office. Interop. Word. dll" file, select it and click "ok" button
Note: here to find "Microsoft. Office. Interop. Word. dll" version must be "11. *. *. *", "*" represent Numbers
Step 3, code
This step is divided into two parts
Part 1, coding for the Report class
I have wrapped this part for the file "Report.cs", which can be used directly
The specific implementation code is as follows :(there are more detailed comments in the code)
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Word;
namespace MYNAMESPACE // This side needs to change its own namespace name
{
classReport
{
private_ApplicationwordApp= null;
private_DocumentwordDoc= null;
public_ApplicationApplication
{
get
{
return wordApp;
}
set
{
wordApp = value;
}
}
public_DocumentDocument
{
get
{
return wordDoc;
}
set
{
wordDoc = value;
}
}
// Create a new document from the template
publicvoidCreateNewDocument(stringfilePath)
{
killWinWordProcess();
wordApp= new ApplicationClass();
wordApp.DisplayAlerts =WdAlertLevel.wdAlertsNone;
wordApp.Visible =false;
objectmissing =System.Reflection.Missing.Value;
objecttemplateName =filePath;
wordDoc= wordApp.Documents.Open(reftemplateName, refmissing,
ref missing, ref missing,ref missing, ref missing, refmissing,
ref missing, ref missing,ref missing, ref missing, refmissing,
ref missing, ref missing,ref missing, ref missing);
}
// Save the new file
publicvoidSaveDocument(stringfilePath)
{
objectfileName =filePath;
objectformat =WdSaveFormat.wdFormatDocument;// Save the format
objectmiss =System.Reflection.Missing.Value;
wordDoc.SaveAs(reffileName, ref format, ref miss,
ref miss, ref miss,ref miss, ref miss,
ref miss, ref miss,ref miss, ref miss,
ref miss, ref miss,ref miss, ref miss,
ref miss);
// Shut down wordDoc . wordApp object
objectSaveChanges =WdSaveOptions.wdSaveChanges;
objectOriginalFormat =WdOriginalFormat.wdOriginalDocumentFormat;
objectRouteDocument =false;
wordDoc.Close(refSaveChanges, refOriginalFormat, refRouteDocument);
wordApp.Quit(refSaveChanges, refOriginalFormat, refRouteDocument);
}
// Insert a value at the bookmark
publicboolInsertValue(stringbookmark, stringvalue)
{
objectbkObj =bookmark;
if(wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
{
wordApp.ActiveDocument.Bookmarks.get_Item(refbkObj).Select();
wordApp.Selection.TypeText(value);
return true;
}
returnfalse;
}
// Insert table ,bookmark bookmarks
publicTableInsertTable(stringbookmark, int rows, int columns,float width)
{
objectmiss =System.Reflection.Missing.Value;
objectoStart =bookmark;
Rangerange =wordDoc.Bookmarks.get_Item(refoStart).Range;// Table insertion location
TablenewTable =wordDoc.Tables.Add(range,rows, columns, ref miss, refmiss);
// Format the table
newTable.Borders.Enable =1; // Borders are allowed, no borders by default ( for 0 The Times wrong, 1 Is the solid line border, 2 , 3 Is the dotted border, subsequent Numbers have not been tried )
newTable.Borders.OutsideLineWidth=WdLineWidth.wdLineWidth050pt;// Border width
if(width != 0)
{
newTable.PreferredWidth=width;// Table width
}
newTable.AllowPageBreaks =false;
returnnewTable;
}
// Merged cell The name of the table , Start the line Numbers , Start column number , End of the line number , The end of the column number
publicvoidMergeCell(Microsoft.Office.Interop.Word.Tabletable, int row1, int column1,int row2, int column2)
{
table.Cell(row1,column1).Merge(table.Cell(row2,column2));
}
// Sets the table content alignment Align In the horizontal direction, Vertical The vertical direction ( Align left, center, and right Align and Vertical The value of -1,0,1)
publicvoidSetParagraph_Table(Microsoft.Office.Interop.Word.Tabletable, int Align, int Vertical)
{
switch(Align)
{
case -1:table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphLeft;break;// The left
case 0: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphCenter;break;// Horizontal center
case 1: table.Range.ParagraphFormat.Alignment=WdParagraphAlignment.wdAlignParagraphRight;break;// Align right
}
switch(Vertical)
{
case -1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalTop;break;// At the top of the alignment
case 0: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalCenter;break;// Vertical center
case 1: table.Range.Cells.VerticalAlignment=WdCellVerticalAlignment.wdCellAlignVerticalBottom;break;// The bottom of the alignment
}
}
// Set the table font
publicvoidSetFont_Table(Microsoft.Office.Interop.Word.Tabletable, string fontName, double size)
{
if(size != 0)
{
table.Range.Font.Size =Convert.ToSingle(size);
}
if(fontName !="")
{
table.Range.Font.Name =fontName;
}
}
// Whether to use borders or not ,n The number of the table ,use Yes or no
publicvoidUseBorder(int n,bool use)
{
if(use)
{
wordDoc.Content.Tables[n].Borders.Enable =1; // Borders are allowed, no borders by default ( for 0 When there is no border, 1 Is the solid line border, 2 , 3 Is the dotted border, subsequent Numbers have not been tried )
}
else
{
wordDoc.Content.Tables[n].Borders.Enable =2; // Borders are allowed, no borders by default ( for 0 When there is no border, 1 Is the solid line border, 2 , 3 Is the dotted border, subsequent Numbers have not been tried )
}
}
// Insert the table 1 line ,n The serial number of the form is from 1 Begin to remember
publicvoidAddRow(int n)
{
objectmiss =System.Reflection.Missing.Value;
wordDoc.Content.Tables[n].Rows.Add(refmiss);
}
// Add to table 1 line
publicvoidAddRow(Microsoft.Office.Interop.Word.Tabletable)
{
objectmiss =System.Reflection.Missing.Value;
table.Rows.Add(refmiss);
}
// Insert the table rows line ,n Is the serial number of the table
publicvoidAddRow(int n, int rows)
{
objectmiss =System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n];
for(inti = 0; i < rows; i++)
{
table.Rows.Add(refmiss);
}
}
// Insert elements into cells in the table, table In the table, row The line number, column Column number, value Inserted element
publicvoidInsertCell(Microsoft.Office.Interop.Word.Tabletable, int row, int column,string value)
{
table.Cell(row,column).Range.Text =value;
}
// Insert elements into cells in the table, n The serial number of the form is from 1 Begin to remember, row The line number, column Column number, value Inserted element
publicvoidInsertCell(int n, int row,int column, string value)
{
wordDoc.Content.Tables[n].Cell(row,column).Range.Text =value;
}
// Insert the table 1 Rows of data, n Is the serial number of the table, row The line number, columns The number of columns. values Insert the value of the
publicvoidInsertCell(int n, int row,int columns, string[] values)
{
Microsoft.Office.Interop.Word.Tabletable = wordDoc.Content.Tables[n];
for(inti = 0; i < columns; i++)
{
table.Cell(row,i + 1).Range.Text =values[i];
}
}
// Insert the picture
publicvoidInsertPicture(stringbookmark, stringpicturePath, floatwidth, float hight)
{
object miss = System.Reflection.Missing.Value;
objectoStart =bookmark;
ObjectlinkToFile =false; // Whether the image is an external link
ObjectsaveWithDocument =true; // Does the image accompany the document 1 The save
objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range;// Image insertion location
wordDoc.InlineShapes.AddPicture(picturePath,ref linkToFile, ref saveWithDocument, refrange);
wordDoc.Application.ActiveDocument.InlineShapes[1].Width=width; // Set the image width
wordDoc.Application.ActiveDocument.InlineShapes[1].Height=hight; // Set image height
}
// insert 1 paragraph ,text For text content
publicvoidInsertText(stringbookmark, stringtext)
{
objectoStart =bookmark;
objectrange =wordDoc.Bookmarks.get_Item(refoStart).Range;
Paragraphwp =wordDoc.Content.Paragraphs.Add(refrange);
wp.Format.SpaceBefore= 6;
wp.Range.Text =text;
wp.Format.SpaceAfter =24;
wp.Range.InsertParagraphAfter();
wordDoc.Paragraphs.Last.Range.Text ="\n";
}
// kill winword.exe process
publicvoidkillWinWordProcess()
{
System.Diagnostics.Process[]processes=System.Diagnostics.Process.GetProcessesByName("WINWORD");
foreach (System.Diagnostics.Processprocess in processes)
{
bool b = process.MainWindowTitle=="";
if (process.MainWindowTitle =="")
{
process.Kill();
}
}
}
}
}
Part 2, the encoding of the generated document
See the code below:
1. You first need to load the template
Report report =new Report();
report.CreateNewDocument(TemPath); // Template path
2. Insert a value
report.InsertValue("Bookmark_value"," World Cup "); // Insert a value at the bookmark "Bookmark_value"
3. Create 1 table
Table table =report.InsertTable("Bookmark_table", 2, 3, 0); // Insert 2 rows and 3 columns in the bookmark "Bookmark_table" for the table with the largest row width
4. Merge cells
report.MergeCell(table, 1, 1, 1, 3); Table name, start row number, start column number, end row number, end column number
5. Add 1 row to the table
report.AddRow(table); / / the name of the table
6. Insert values into cells
report.InsertCell(table, 2, 1,"R2C1"); // Table name, row number, column number, value
7. Set the alignment of the text in the table
report.SetParagraph_Table(table, -1, 0); // Align left horizontally and center vertically
8. Set the table font
report.SetFont_Table(table," Song Style ", 9); // The body weighs 9 pounds
9. Add 1 row to an existing table
report.AddRow(1); // Add 1 row to the 1st table in the template
10. Determine if an existing table USES borders
report.UseBorder(1,true); // The first table in the template USES a solid border
11. Add multiple rows to an existing table
report.AddRow(1, 2); // Insert 2 rows into the first table in the template
Insert 1 row of data into an existing table
[] string ={Premier League, Serie A, Bundesliga, La Liga, Ligue 1}
report.InsertCell(1, 2, 5,values); // Insert data into row 2 and column 5 of the first table in the template
13. Insert an image
string picturePath = @"C:\Documents and \Administrator\ desktop \ 1.ES155en ";
report.InsertPicture("Bookmark_picture",picturePath, 150, 150); // Bookmark location, image path, image width, image height
14. Insert a paragraph
"Long-term computer operators should eat more fresh vegetables and fruits, and increase the intake of vitamins A, B1, C and E. To prevent corneal dryness, eye dryness, impaired vision and even night blindness, the electronic brain operator should eat more foods rich in vitamin A, such as bean products, fish, milk, walnuts, green vegetables, Chinese cabbage, water spinach, tomatoes and fresh fruits. ;
report.InsertText("Bookmark_text",text);
15. Finally, save the document
report.SaveDocument(RepPath); // Document path
Step 4, run the program to generate the document and view the generated document
Hopefully this article has helped you with your C# programming.