Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Net document manipulation component DocX how to use

2025-02-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Today, I will talk to you about how to use the .NET document manipulation component DocX, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something from this article.

In the current software projects, the operation of documents will be more often used to record and count relevant business information. Because the system itself provides the relevant operation to the document, it greatly simplifies the workload of software users to a certain extent.

In the .NET project, if users put forward the requirements for relevant document operation, developers will often use the plug-ins provided by Microsoft, which simplifies the developer's workload to a certain extent, but also brings some troubles to users. For example, if you need to install a huge office, the user experience will be reduced a lot, and in China, many people still use wps. This makes it very difficult for some users who only have wps installed, and there is a NPOI component for the operation of Excel.

I. Overview of DocX components:

DocX is a. Net library that allows developers to work with Word 2007 Universe 2010 Universe 2013 files in a simple and intuitive way. DocX is fast, lightweight, and best of all, it doesn't need to install Microsoft Word or Office. The DocX component not only fulfills the general requirements for documents, such as creating documents, tables and text, but also creates graphical reports. DocX makes it a simple task to create and manipulate documents.

It does not use the COM library, nor does it require Microsoft Office to be installed. When using DocX components, you need to install the .NET Framework 4.0 and Visual Studio 2010 or later in order to use DocX.

The main features of DocX:

(1)。 Insert, delete, or replace text in a document. All standard text formats are available. Font {series, size, color}, bold, italic, underline, delete line, script {sub, super}, highlighted.

(2)。 Paragraph properties are displayed. Indent in the direction of LeftToRight or RightToLeft;; compare.

(3) .DocX also supports: pictures, hyperlinks, tables, headers and footers, custom properties.

This is the end of the information about the DocX component. For more in-depth information, you can go to: https://docx.codeplex.com/.

2. Parsing of DocX-related classes and methods:

This article will parse the source code of DocX and decompile the DLL file using .NET Reflector to view the source code. 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: add information to a paragraph.

Public Paragraph Append (string text) {List content = HelperFunctions.FormatInput (text, null); base.Xml.Add (content); this.runs = base.Xml.Elements (XName.Get ("r", DocX.w.NamespaceName)). Reverse (). Take (content.Count ()). ToList (); return this;} public Paragraph Bold () {this.ApplyTextFormattingProperty (XName.Get ("b", DocX.w.NamespaceName), string.Empty, null); return this;}

3.Table.InsertTableAfterSelf: inserts data into a 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 ());}

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 graph.

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 {get;} public ValueAxis ValueAxis {get; private set;} public bool View3D {get; set;} public XDocument Xml {get; private set;}}

The AddLegend (), AddSeries (), RemoveLegend () methods of 6.Chart parse:

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 () = = this.MaxSeriesCount) {throw new InvalidOperationException ("Maximum series for this chart is" + this.MaxSeriesCount.ToString () + "and have exceeded!");} this.ChartXml.Add (series.Xml);} public void RemoveLegend () {this.Legend.Xml.Remove (); this.Legend = null;}

The above is some simple parsing of some methods of the DocX component. If you need to know more about the method implementation code, you can download and view it yourself.

3. Examples of DocX function implementation:

1. Create a chart:

/ create bar graph / document path / bind data / category name / value name / icon title public static bool BarChart (string path,Dictionary 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 graphic property settings, BarDirection graphic direction enumeration, BarGrouping graphic grouping enumeration var c = new BarChart {BarDirection = BarDirection.Column, BarGrouping = BarGrouping.Standard, GapWidth = 400} / / set chart legend location 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 the document title document.InsertParagraph (title) .FontSize (20); document.InsertChart (c); document.Save (); return true;}} catch (Exception ex) {throw new Exception (ex.Message);}}

two。 Create a document with hyperlinks, images, and tables.

/ / create a document with hyperlinks, images, and tables. / document save path / loaded image path / url address 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);} 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] .Paragraph [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 is a cool") .AppendHyperlink (link) .append ("."); p1.AppendLine () P1.AppendLine ("Check out this picture") .AppendPicture (picture) .append ("its funky don't you think?"); p1.AppendLine (); p1.AppendLine ("Can you check this Table of 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. Writes the specified content to the document:

/ / write the specified content to the document / load file path / / write file content / save file path public static void 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);} try {using (var document = DocX.Load (path)) {/ / ensure that this 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)); / / get the graphic objects of this bitmap, which provide drawing functions. Var g = Graphics.FromImage (b); / / draw string content g.DrawString (content, new Font ("Tahoma", 20), Brushes.Blue, new PointF (0,0)) / / use the create\ write stream to save the bitmap to the document. B.Save (img.GetStream (FileMode.Create, FileAccess.Write), ImageFormat.Png);} else {document.SaveAs (savePath);} catch (Exception ex) {throw new Exception (ex.Message) }} after reading the above, do you have any further understanding of how to use the .NET document manipulation component DocX? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report