Objective
I believe everyone should have experience, in the current software projects, will be more use of the operation of the document, for recording and statistics related business information. Because the system itself provides the related operation to the document, it greatly simplifies the work of the software user to some extent.
In a. NET project, if a user raises the need for related document operations, developers are more likely to use Microsoft's own plug-ins to some extent simplify the work of developers, but also bring some trouble to the user, such as the need to install a large office, the user experience will be reduced a lot of And at home, a lot of people are still using WPS, which led to a part of the user only installed WPS is very difficult, in the operation of Excel, there is a npoi component. Then maybe someone will ask if there is any way to solve these problems, the answer is yes, that is the "DocX" component that needs to be introduced today, and then we'll take a look at the functionality and usage of this component.
I. Docx Components Overview:
Docx is a. NET library that allows developers to work with Word 2007/2010/2013 files in a simple and intuitive manner. Docx is fast, lightweight, and, best of all, it does not require installation of Microsoft Word or office. The Docx component can not only complete general requirements for documents, such as creating documents, creating tables and text, and creating graphical reports. Docx makes creating and manipulating documents a simple task.
It does not use a COM library, nor does it need to install Microsoft Office. When using the Docx component, you need to install the. NET Framework 4.0 and Visual Studio 2010 or later in order to use the docx.
main features of docx:
(1). Inserts, deletes, or replaces text in the document. All standard text formats are available. Font {series, size, color}, bold, italic, underline, strikethrough, script {child, Super}, highlighted.
(2). Paragraph properties are displayed. N LeftToRight
. A direction or RightToLeft
indent;
(3). Docx also supports: pictures, hyperlinks, tables, headers and footers, custom attributes.
Relevant information about the Docx component is introduced here, and if you need more in-depth information about it, you can enter: https://docx.codeplex.com/.
Two. Docx related class and method analysis:
This article will combine the source code of Docx to parse, use the. NET reflector to decompile the DLL file, in order to view the source. Add the DLL file to the. NET Reflector and click Open File.
1.docx.create (): Create a document.
public static DocX Create (Stream stream)
{
MemoryStream stream2 = new MemoryStream ();
Postcreation (ref Package.Open (STREAM2, FileMode.Create, FileAccess.ReadWrite));
DocX cx = Load (stream2);
Cx.stream = stream;
return CX;
}
2.paragraph.append: Adds information to a paragraph.
Public Paragraph Append (string text)
{
list<xelement> content = helperfunctions.formatinput (text, NULL) ;
Base. Xml.add (content);
This.runs = base. Xml.elements (Xname.get ("R", Docx.w.namespacename)). Reverse<xelement> (). Take<xelement> (content. Count<xelement> ()). Tolist<xelement> ();
return this;
}
Public Paragraph Bold ()
{this
. Applytextformattingproperty (Xname.get ("B", Docx.w.namespacename), String. Empty, null);
return this;
}
3.table.inserttableafterself: Inserts data into the table.
public override Table inserttableafterself (int rowcount, int coloumncount)
{return
base. Inserttableafterself (rowcount, coloumncount);
}
Public virtual Table inserttableafterself (int rowcount, int coloumncount)
{
XElement content = Helperfunctions.createtable (rowcount, coloumncount);
Base. Xml.addafterself (content);
return new Table (base. Document, base. Xml.elementsafterself (). First<xelement> ());
}
4.CustomProperty: Custom Attributes.
public class CustomProperty
{
//Fields
private string name;
private string type;
Private object value;
Methods Public
CustomProperty (string name, bool value);
Public CustomProperty (string name, DateTime value);
Public CustomProperty (string name, double value);
Public CustomProperty (string name, int value);
Public CustomProperty (string name, string value);
Private CustomProperty (string name, String type, object value);
Internal CustomProperty (string name, String type, string value);
Properties public
string Name {get;}
Internal string Type {get;}
Public object Value {get;}
}
5.BarChart: Create a bar chart.
public class Barchart:chart {//Methods public barchart ();
protected override XElement Createchartxml ();
Properties public bardirection bardirection {get; set;}
Public bargrouping bargrouping {get; set;}
public int Gapwidth {get; set;}}
Public abstract class Chart {//Methods public Chart ();
public void Addlegend ();
public void Addlegend (chartlegendposition position, bool overlay);
public void Addseries (Series Series);
Protected abstract XElement createchartxml ();
public void Removelegend ();
Properties public Categoryaxis Categoryaxis {get; private set;}
Protected XElement Chartrootxml {get; private set;}
Protected XElement Chartxml {get; private set;}
Public Displayblanksas Displayblanksas {get; set;}
Public virtual bool Isaxisexist {get;}
Public ChartLegend Legend {get; private set;}
Public virtual short Maxseriescount {get;}
Public list<series> Series {get;}
Public Valueaxis Valueaxis {get; private set;} Public BoOL view3d {get; set;} Public XDocument Xml {get; private set;}}
6.Chart addlegend (), Addseries (), Removelegend () method Resolution:
public void Addlegend (chartlegendposition position, bool overlay)
{
if (this. Legend!= null)
{this
. Removelegend ();
}
This. Legend = new ChartLegend (position, overlay);
This. Chartrootxml.add (this. legend.xml);
}
public void Addseries (Series Series)
{
if (this. Chartxml.elements (Xname.get ("Ser", Docx.c.namespacename)). count<xelement> () = = this. Maxseriescount)
{
throw new InvalidOperationException ("Maximum series for this chart are" + this. Maxseriescount.tostring () + "and have exceeded!");
}
This. Chartxml.add (series. XML);
}
public void Removelegend ()
{this
. Legend.Xml.Remove ();
This. Legend = null;
}
These are some simple parsing of some of the methods of the Docx component, and you can download and view it yourself if you need to know more ways to implement the code.
Three. docx Function Implementation Example:
1. Create a chart:
<summary>///Create bar///</summary>///<param name= "path" > Document path </param>///<para M name= "Dicvalue" > Binding Data </param>///<param name= "CategoryName" > Category name </param>///<param name= "V Aluename "> Value name </param>///<param name=" title "> icon title </param> public static bool Barchart (String Pat H,dictionary<string, icollection> dicvalue,string categoryname,string valuename,string title) {if (string).
IsNullOrEmpty (Path)) {throw new ArgumentNullException (path);
} if (dicvalue = = null) {throw new ArgumentNullException ("Dicvalue"); } if (string.
IsNullOrEmpty (CategoryName)) {throw new ArgumentNullException (CategoryName); } if (string.
IsNullOrEmpty (ValueName)) {throw new ArgumentNullException (VALUENAME); } if (string.
IsNullOrEmpty (title)) {throw new ArgumentNullException (title);
try {using (var document = docx.create (path)) { Barchart Graphics property settings, Bardirection graphics Direction enumeration, Bargrouping graph grouping enumeration var c = new Barchart {bardirection = bardirection.
Column, bargrouping = bargrouping.standard, gapwidth = 400};
Sets the chart legend position C.addlegend (Chartlegendposition.bottom, false);
Write icon data foreach (var chartData in Dicvalue) {var series = new series (Chartdata.key); Series.
Bind (Chartdata.value, CategoryName, ValueName);
C.addseries (series); //Set document title documents. InsertParagraph (title).
FontSize (20); Document.
Insertchart (c); Document.
Save ();
return true; } catch (Exception ex) {throw new Exception (ex.
message); }
}
2. Create a document with hyperlinks, images, and tables.
<summary>///Create a document with hyperlinks, images, and tables. </summary>///<param name= "path" > Document save path </param>///<param name= "ImagePath" > Loaded picture path </ param>///<param name= "url" >url address </param> public static void Hyperlinksimagestables (String path,string Imagepath,string URL) {if (string).
IsNullOrEmpty (Path)) {throw new ArgumentNullException (path); } if (string.
IsNullOrEmpty (ImagePath)) {throw new ArgumentNullException (ImagePath); } if (string.
IsNullOrEmpty (URL)) {throw new ArgumentNullException (URL); The try {using (var document = docx.create (path)) {var link = document.
AddHyperlink ("link", new Uri (URL)); var table = document.
AddTable (2, 2); Table.
design = Tabledesign.colorfulgridaccent2; Table.
Alignment = Alignment.center; Table. Rows[0]. Cells[0]. Paragraphs[0].
Append ("1"); Table. Rows[0]. CELLS[1]. Paragraphs[0].
Append ("2"); Table. ROWS[1]. Cells[0]. Paragraphs[0].
Append ("3"); Table. ROWS[1]. CELLS[1]. Paragraphs[0].
Append ("4"); var newrow = table. InsertRow (table.
ROWS[1]);
Newrow.replacetext ("4", "5"); var image = document.
AddImage (ImagePath); var picture = image.
Createpicture (); Picture.
rotation = 10; Picture.
Setpictureshape (Basicshapes.cube); var title = document. InsertParagraph (). Append ("Test"). FontSize (20).
Font (New FontFamily ("Comic Sans MS")); Title.
Alignment = Alignment.center; var p1 = document.
InsertParagraph (); P1. Appendline ("This line contains a"). Append ("bold"). Bold ().
Append ("word."); P1. Appendline ("Here's a cool"). Appendhyperlink (link).
Append ("."); P1.
Appendline (); P1. Appendline ("Check out the picture"). Appendpicture (picture).
Append ("Its funky Don t"); P1.
Appendline (); P1.
Appendline ("Can Check this Table's figures for me?"); P1.
Appendline (); P1.
Inserttableafterself (table); var P2 = document.
InsertParagraph (); P2.
Appendline ("Is it correct?"); Document.
Save (); } catch (Exception ex) {throw new Exception (ex.
message); }
}
3. Write the specified content to the document:
<summary>///writes the specified content to the document///</summary>///<param name= "path" > Load file path </param>///&L T;param name= "Content" > Write to File contents </param>///<param name= "Savepath" > Save file path </param> public static VO ID programmaticallymanipulateimbeddedimage (string path, string content, String Savepath) {if (string).
IsNullOrEmpty (Path)) {throw new ArgumentNullException (path); } if (string.
IsNullOrEmpty (content)) {throw new ArgumentNullException (content); } if (string.
IsNullOrEmpty (Savepath)) {throw new ArgumentNullException (Savepath);
The try {using (var document = Docx.load (path)) {//ensures that the document has at least one image. if (document. Images.any ()) {var img = document.
Images[0];
Writes the content to the picture. var B = new Bitmap (img.
GetStream (FileMode.Open, FileAccess.ReadWrite));
Gets the graphic object for this bitmap, which provides drawing functionality.
var g = Graphics.fromimage (b);
Draw string Contents g.drawstring (content, New Font ("Tahoma",), Brushes.blue, new PointF (0, 0));
Use the Create \ Write stream to save the bitmap in the document. B.save (IMG.
GetStream (FileMode.Create, FileAccess.Write), imageformat.png); else {document.
SaveAs (Savepath); Exception ex) {throw new Exception (ex.
message); }
}
Summarize
The above is a simple parsing of the API for the Docx component, along with a few ways to create documents and create diagrams for developers to refer to. I hope the content of this article for everyone's study or work can bring certain help, if there is doubt you can message exchange.