


C# uses NPOI to generate Word documents (according to template)
Aug 07, 2018 am 10:52 AM The project needs to integrate word export. When I was doing it, there were not many online document resources and it was quite messy, so I checked, sorted it out, made a record, and also shared some basic operations of NPOI operating Word documents with those in need. friend.
This article includes the operations of generating Word text, table operations, and picture operations, which are all basic operations for generating Word.
The following is just my personal understanding. If you have any better ideas, please feel free to add.
VS2017, right-click the solution, manage NuGet packages, search and install the NPOI package for the project, and quote:
using NPOI.XWPF.UserModel;
This article uses the NPOI version For 2.3.0
Let’s get to the point··
1. Get the template (XWPFDocument doc)
Use the template, first get the template, and then instantiate the obtained template as Edit the document object of NPOI:
using (FileStream stream = File.OpenRead("template file address")){
XWPFDocument doc = new XWPFDocument(stream);
//Process doc, code control editing document.
}
After processing the doc, generate a new file, write it into the doc, and complete the word generation.
FileStream file = new FileStream(generated file path file name, FileMode.Create, FileAccess.Write);
doc.Write(file);
file.Close();
doc is what we get to all contents of the template.
Another point is that the templates used by this editor are all docx suffix files. If doc is modified, an error will be reported when reading docx, and it needs to be saved as a doxc document.
2. Text processing (XWPFParagraph para)
doc.Paragraphs Gets all the paragraph objects in the document;
para.ParagraphText Gets the text data of the paragraph;
para.ReplaceText (text to be replaced, replacement text) Replace the text of the paragraph (the key to template implementation)
Official reference document of XWPFParagraph
3. Table processing ( XWPFTable table)
doc.Tables Gets all table objects in the document;
It is necessary to say more here, doc.Tables only gets the outermost table in Word, not including the nested ones layer.
You can use cell.Tables to get nested cells;
(1) Table row processing (XWPFTableRow row)
row.Rows Get all the rows of the table;
(2) Table cell processing (XWPFTableCell cell) row.GetTableICells() ;
Get all the cells in the table row;
After getting the cell, you can get the cell Text paragraphs (Paragraphs) in and perform text replacement
(3) Merge row cells horizontally
CT_Tc cttcofRowThird = cell.GetCTTc(); CT_TcPr ctProfRowThird = cttcofRowThird.AddNewTcPr(); ctProfRowThird.gridSpan = new CT_DecimalNumber(); ctProfRowThird.gridSpan.val = num.ToString();//合并num列
(4) Merge column cells vertically
List<XWPFTableRow> rows所有要合并的行的XWPFTableRow對(duì)象集合。 XWPFTableCell cellFirstofThird = 第一行要合并的單元格對(duì)象; CT_Tc cttcFirstofThird = cellFirstofThird.GetCTTc(); CT_TcPr ctPrFirstofThird = cttcFirstofThird.AddNewTcPr(); ctPrFirstofThird.AddNewVMerge().val = ST_Merge.restart;//開始合并行 ctPrFirstofThird.AddNewVAlign().val = ST_VerticalJc.center;//垂直 cttcFirstofThird.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center; for (int i = 1; i < rows.Count; i++) { XWPFTableCell cellfirstofRow = 第i行要合并的單元格對(duì)象; CT_Tc cttcfirstofRow = cellfirstofRow.GetCTTc(); CT_TcPr ctPrfirstofRow = cttcfirstofRow.AddNewTcPr(); ctPrfirstofRow.AddNewVMerge().val = ST_Merge.@continue;//繼續(xù)合并行 ctPrfirstofRow.AddNewVAlign().val = ST_VerticalJc.center;//垂直 }
4. Image processing
The image insertion of the NPOI version 2.3.0 does not integrate the modification of the xml file, so it needs to be compiled by handwriting (of course, I copied it).
using (FileStream fsImg = new FileStream(圖片路徑, FileMode.Open, FileAccess.Read, FileShare.None)) { var picID = doc.AddPictureData(fsImg, (int)NPOI.XWPF.UserModel.PictureType.JPEG); string picXml = "" + " <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" + " <pic:nvPicPr>" + " <pic:cNvPr id=\"" + "0" + "\" name=\"Generated\"/>" + " <pic:cNvPicPr/>" + " </pic:nvPicPr>" + " <pic:blipFill>" + " <a:blip r:embed=\"" + id + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" + " <a:stretch>" + " <a:fillRect/>" + " </a:stretch>" + " </pic:blipFill>" + " <pic:spPr>" + " <a:xfrm>" + " <a:off x=\"0\" y=\"0\"/>" + " <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" + " </a:xfrm>" + " <a:prstGeom prst=\"rect\">" + " <a:avLst/>" + " </a:prstGeom>" + " </pic:spPr>" + " </pic:pic>"; XWPFParagraph par = cell.AddParagraph();//創(chuàng)建段落對(duì)象(可以在doc加也可在cell加) par.Alignment = ParagraphAlignment.CENTER;//居中 XWPFRun run = par.CreateRun(); CT_Inline inline = run.GetCTR().AddNewDrawing().AddNewInline(); inline.graphic = new CT_GraphicalObject { graphicData = new CT_GraphicalObjectData { uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" } }; try { inline.graphic.graphicData.AddPicElement(picXml); } catch (XmlException xe) { throw xe; } NPOI.OpenXmlFormats.Dml.WordProcessing.CT_PositiveSize2D extent = inline.AddNewExtent(); extent.cx = width; extent.cy = height; NPOI.OpenXmlFormats.Dml.WordProcessing.CT_NonVisualDrawingProps docPr = inline.AddNewDocPr(); docPr.id = 1; docPr.name = "Image" + id; }
I’ll stop here today, and I’ll add more later if I gain more.
Related recommendations:
The above is the detailed content of C# uses NPOI to generate Word documents (according to template). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ??such as Python. Be careful when modifying and back up the original files.

Methods to convert XML to JSON include: writing scripts or programs in programming languages ??(such as Python, Java, C#) to convert; pasting or uploading XML data using online tools (such as XML to JSON, Gojko's XML converter, XML online tools) and selecting JSON format output; performing conversion tasks using XML to JSON converters (such as Oxygen XML Editor, Stylus Studio, Altova XMLSpy); converting XML to JSON using XSLT stylesheets; using data integration tools (such as Informatic

C# multi-threaded programming is a technology that allows programs to perform multiple tasks simultaneously. It can improve program efficiency by improving performance, improving responsiveness and implementing parallel processing. While the Thread class provides a way to create threads directly, advanced tools such as Task and async/await can provide safer asynchronous operations and a cleaner code structure. Common challenges in multithreaded programming include deadlocks, race conditions, and resource leakage, which require careful design of threading models and the use of appropriate synchronization mechanisms to avoid these problems.

There are three ways to convert XML to Word: use Microsoft Word, use an XML converter, or use a programming language.

Use most text editors to open XML files; if you need a more intuitive tree display, you can use an XML editor, such as Oxygen XML Editor or XMLSpy; if you process XML data in a program, you need to use a programming language (such as Python) and XML libraries (such as xml.etree.ElementTree) to parse.

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.
