C # uses NPOI to generate Word documents (by template)

Source: Internet
Author: User
Tags mongodb postgresql redis


Project needs to integrate word export, do when the online document resources are not many, but also more messy, so check the check, sorting out, do a record, also by the way Npoi operation Word document some basic operations to share to the needs of friends.



This article includes actions to generate word text for Word, the actions of the table, and the actions of the picture, which are some of the operations that generate word basics.



The following is just my personal understanding of what you have in mind to welcome the supplement.



VS2017, right-click Solutions, manage NuGet packages, search for and install Npoi packages for projects, and reference:
Using Npoi. XWPF. Usermodel;
This series uses Npoi version 2.3.0
Get down to the Chase ·
First, get the template (xwpfdocument doc)
Using a template, you first get the template and then instantiate the obtained template as a Npoi Document object for editing:
using (FileStream stream = File.openread ("Template file Address")) {
Xwpfdocument doc = new xwpfdocument (stream);
Process doc, code control edit document.
}
After processing doc, generate a new file, write to Doc, and build word complete.
FileStream file = new FileStream (makefile path + file name, FileMode.Create, FileAccess.Write);
Doc. Write (file);
File. Close ();
Doc is all the content of the template we get.
There's a little bit of this. The template is docx suffix file, doc modified docx read error, need to save as DOXC document.
Second, 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 (the text to be replaced, replace text) replaces the text of the paragraph (the key that the template can achieve)



Xwpfparagraph's official Reference document



Third, form processing (xwpftable table)
Doc. Tables gets all the table objects in the document;
There is a need for more than one mouth, Doc. Tables gets only the outermost table in Word and does not contain nested inner layers.
Get nested cells to use the cell. Tables;
(i) Table row processing (xwpftablerow row)
Row. Rows gets all rows of the table;
(ii) Table cell processing (Xwpftablecell cell)
row.GetTableICells() ;Gets all the cells of the table row;
After you get to the cell, you can get the text paragraph (paragraphs) in the cell and replace the text
(iii) Horizontal merging of row cells






CT_Tc cttcofRowThird = cell.GetCTTc();

CT_TcPr ctProfRowThird = cttcofRowThird.AddNewTcPr();

ctProfRowThird.gridSpan = new CT_DecimalNumber();

ctProfRowThird.gridSpan.val = num.ToString();//Merge num columns


(iv) vertically merged column cells





List<XWPFTableRow> rows A collection of XWPFTableRow objects for all rows to be merged.

 

XWPFTableCell cellFirstofThird = the first row of cell objects to be merged;

CT_Tc cttcFirstofThird = cellFirstofThird.GetCTTc();

CT_TcPr ctPrFirstofThird = cttcFirstofThird.AddNewTcPr();

ctPrFirstofThird.AddNewVMerge().val = ST_Merge.restart;//Start merge line

ctPrFirstofThird.AddNewVAlign().val = ST_VerticalJc.center;//Vertical

cttcFirstofThird.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;

For (int i = 1; i < rows.Count; i++)

{

     XWPFTableCell cellfirstofRow = the cell object to be merged in the i-th row;

     CT_Tc cttcfirstofRow = cellfirstofRow.GetCTTc();

     CT_TcPr ctPrfirstofRow = cttcfirstofRow.AddNewTcPr();

     ctPrfirstofRow.AddNewVMerge().val = ST_Merge.@continue;//Continue merge rows

     ctPrfirstofRow.AddNewVAlign().val = ST_VerticalJc.center;//Vertical

} 

Fourth, image processing



The 2.3.0 version of Npoi's picture was inserted without the modification of the integrated XML file, so the handwriting code was required (of course, I copied it).






Using (filestream fsimg = new filestream (picture path, filemode.open, fileaccess.read, fileshare.none))

{

Var picid = doc.addpicturedata (fsimg, (int) npoi.xwpf.usermodel.picturepepe.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/ReranceShipS \" /> "

                    + "<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: pRSTIGEOM>"

                    + "</ pic: SPPR>"

                    + "</ pic: pic>";

                XWPFPARAGRAGRAGRAGRAPH (); // Create a paragraph object (you can add in Cell) in DOC

                Par.alignment = paragraphaloadment.center; //

                Xwpfrun run = par.createrun ();

                CT_INLINE INLINE = Run.getctr (). Addnewdrawing (). Addnewinline ();

                Inline.graphic = new CT_GRAPHICOBJECT

                {

                    GraphicData = new CT_GRAPHICOBJECTDATA

                    {

                        URI = "http://schemas.openxmlformats.org/drawingml/2006/picture"

                    }

                }

                Try

                {

                    Inline.graphic.graphicdata.addpictElement (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;

}

The Arrived here today, and there is a harvest to be added later.


Alibaba Cloud Hot Products

Elastic Compute Service (ECS) Dedicated Host (DDH) ApsaraDB RDS for MySQL (RDS) ApsaraDB for PolarDB(PolarDB) AnalyticDB for PostgreSQL (ADB for PG)
AnalyticDB for MySQL(ADB for MySQL) Data Transmission Service (DTS) Server Load Balancer (SLB) Global Accelerator (GA) Cloud Enterprise Network (CEN)
Object Storage Service (OSS) Content Delivery Network (CDN) Short Message Service (SMS) Container Service for Kubernetes (ACK) Data Lake Analytics (DLA)

ApsaraDB for Redis (Redis)

ApsaraDB for MongoDB (MongoDB) NAT Gateway VPN Gateway Cloud Firewall
Anti-DDoS Web Application Firewall (WAF) Log Service DataWorks MaxCompute
Elastic MapReduce (EMR) Elasticsearch

Alibaba Cloud Free Trail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.