Foreword:

I recently used NPOI to export Word documents. There are many ways to export Word documents using .NET Core. In the end, why did I choose NPOI to implement this feature? First, NPOI is an open source, free and easy to use third-party framework (and now supports .NET Core, GitHub source address:
https://github.com/tonyqus/ Npoi

). Because I used to export Execl with NPOI before, the first time I used NPOI to export Word documents, I really didn’t have a clue. First look at the source code in GitHub has a simple Word export example, and then read a lot of online NPOI export Word documents, found that a feature on the Internet seems to be almost the same, for me, these cases on the Internet can fully I realized this function, but I feel that these cases on the Internet have instantiated paragraphs, forms and settings related styles for NPOI (maybe because they are stupid), and if you use online methods to implement my functions, the amount of code will be It’s big, and I feel that the code is very redundant (I am a person who is pursuing code succinct, how can I tolerate such a thing happening!), so by looking up some information and my own understanding, I want to use Word to export Word when using NPOI. Some paragraphs involved, the table styles are related to comments, and the creation of examples of paragraphs and forms, setting text, fonts, and alignment are encapsulated (in order to write less code), a complete case download will be attached at the end of the article. address.

1 introduce NPOI NuGet:

Release Notes:

NPOI 2.4.1 (note that the postures that may be used in different versions are a little different)

The package manager console enters the command to install:

Install-Package NPOI -Version 2.4.1

Install through NuGet Management Solution:

2, the exported Work document content format style:

3, the XWPFRun text object creation and attribute summary in NPOI:

XWPFRun text object description:

XWPFRun is the text object of the paragraph. The paragraph object is created first to create a text object based on the paragraph object and set the relevant text style.

As follows:

 

 

        ///  <summary> 
        /// Create a paragraph object in a word document and set the basic style of the paragraph text (font size, font, font color, font alignment position)
         ///  </summary> 
        ///  <param name= "document"> document document object </param> 
        ///  <param name="fillContent"> The content of the first text object filled in the paragraph </param> 
        ///  <param name="isBold"> is bold < /param> 
        ///  <param name="fontSize"> Font Size </param> 
        ///  <param name="fontFamily"> Font </param> 
        ///  <param name="paragraphAlign"> Paragraph Arrangement ( Left aligned, centered, right aligned) </param>
        ///  <returns></returns> 
        private  staticXWPFParagraph ParagraphInstanceSetting(XWPFDocument document, string fillContent, bool isBold, int fontSize, string fontFamily, ParagraphAlignment paragraphAlign,)
        {
            XWPFParagraph paragraph = document.CreateParagraph(); // Create paragraph object 
            paragraph.Alignment = paragraphAlign; // Text display position, paragraph arrangement (left aligned, centered, right aligned) 

            XWPFRun xwpfRun = paragraph.CreateRun(); // Create paragraph Text object 
            xwpfRun.IsBold = isBold; // Text bold 
            xwpfRun.SetText(fillContent); // Fill content 
            xwpfRun.FontSize = fontSize; // Set the text size 
            xwpfRun.SetFontFamily(fontFamily, FontCharRange.None); // Set the title Styles such as: (Microsoft Yahei, Lishu, 楷 body) according to their needs, 
            return paragraph;
        }

 

 

 

There are many attributes of the XWPFRun text object. Below I briefly explain several commonly used methods:

XWPFParagraph paragraph = document.CreateParagraph();
XWPFRun xwpfRun= paragraph.CreateRun();
xwpfRun.IsBold = isBold;
xwpfRun.SetText(fillContent);
xwpfRun.FontSize = fontSize;
xwpfRun.SetFontFamily(fontFamily, FontCharRange.None);
xwpfRun.SetColor("BED4F1");
xwpfRun.IsDoubleStrikeThrough=true;
xwpfRun.IsStrikeThrough = true;
xwpfRun.SetUnderline(UnderlinePatterns.Dash);
xwpfRun.SetTextPosition(20);
xwpfRun.AddBreak();
xwpfRun.AddTab();
xwpfRun.AddCarriageReturn();
xwpfRun.IsImprinted = true;
xwpfRun.IsItalic=true;
xwpfRun.Subscript = VerticalAlign.SUBSCRIPT;

For more tips on using the XWPFRun property in NPOI, read the source code:

Source code:
https://github.com/tonyqus/npoi/blob/master/ooxml/XWPF/Usermodel/XWPFRun.cs

4, NPOI generates Word complete code:

 

 

Using Microsoft.AspNetCore.Hosting;
 using NPOI.OpenXmlFormats.Wordprocessing;
 using NPOI.XWPF.UserModel;
 using System;
 using System.IO;

namespace Export.Services
{
    Public  class NpoiWordExportService
    {
        Private  static IHostingEnvironment _environment;

        Public NpoiWordExportService(IHostingEnvironment iEnvironment)
        {
            _environment = iEnvironment;
        }

        #regionGenerate word

        ///  <summary> 
        ///   Generate a word document and save the ///  </summary> 
        ///  <param name="savePath"> save path </ 
        b> in the SaveWordFile folder under the static resource folder (wwwroot)
         Param> public  bool SaveWordFile( out  string savePath)
        {
            savePath = "" ;
             try
            {
                String currentDate = DateTime.Now.ToString( " yyyyMMdd " );
                 string checkTime = DateTime.Now.ToString( " yyyy year MM month dd day " ); // Check time
                 // save file to static resource wwwroot, use absolute path path 
                Var uploadPath = _environment.WebRootPath + " /SaveWordFile/ " + currentDate + " / " ; // >>> is equivalent to HttpContext.Current.Server.MapPath("")

                String workFileName = checkTime + " Chasing Time Enterprise Staff Training Assessment Statistics Record Table " ;
                 string fileName = string .Format( " {0}.docx " , workFileName, System.Text.Encoding.UTF8);

                If (! Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // Create a file stream object by using the file stream, write the content to the file stream, and save it as a Word document format 
                using ( var stream = new FileStream(Path.Combine(uploadPath, fileName), FileMode.Create, FileAccess.Write ))
                {
                    / / Create document document object object instance 
                    XWPFDocument document = new XWPFDocument ();

                    /* *
                     * Here I greatly reduce the redundancy of the code by setting the SetParagraph (paragraph) instance creation and paragraph style formatting in the public Word document.
                     * Avoid creating a paragraph instance and setting the basic style of the paragraph every time you use a paragraph
                     * (As follows, ParagraphInstanceSetting is for paragraph instance creation and style setting, the latter index is represented as the current number of paragraphs, the index starts from 0)
                     */ 
                    // text title 
                    document.SetParagraph(ParagraphInstanceSetting(document, workFileName, true , 19 , " 宋体" , ParagraphAlignment.CENTER), 0 );

                    // TODO: This line needs to display two texts 
                    document.SetParagraph(ParagraphInstanceSetting(document, $ " number:20190927101120445887 " , false , 14 , " 宋体" , ParagraphAlignment.CENTER, true , $ "     Check time: {checkTime} " ) , 1 );


                    document.SetParagraph(ParagraphInstanceSetting(document, " Registration Authority: Enterprise Employee Supervision and Inspection Agency " , false , 14 , " Song " , ParagraphAlignment.LEFT), 2 );


                    #regionDocument The first table object instance // Create a table object instance in the
                     document 
                    XWPFTable firstXwpfTable = document.CreateTable( 4 , 4 ); // Display the number of rows and columns rows: 3 rows, cols: 4 columns 
                    firstXwpfTable.Width = 5200 ; // total width 
                    firstXwpfTable.SetColumnWidth ( 0 , 1300 ); / * set the column width * / 
                    firstXwpfTable.SetColumnWidth ( . 1 , 1100 is ); / * set the column width * / 
                    firstXwpfTable.SetColumnWidth ( 2 ,1400 ); /* set column width * / 
                    firstXwpfTable.SetColumnWidth ( 3 , 1400 ); / * set column width * /

                    // The first row of the Table table is displayed... the latter is the same, only the number of rows in 
                    GetRow is changed firstXwpfTable.GetRow ( 0 ).GetCell( 0 ).SetParagraph(Set,TableParagraphInstanceSetting(document, firstXwpfTable, " company name " , ParagraphAlignment .CENTER, 40 , true ));
                    firstXwpfTable.GetRow( 0 ).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Chase Time " , ParagraphAlignment.CENTER, 40 , false ));
                    firstXwpfTable.GetRow( 0 ).GetCell( 2 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Enterprise Address " , ParagraphAlignment.CENTER, 40 , true ));
                    firstXwpfTable.GetRow( 0 ).GetCell( 3 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Hunan Province - Changsha City - Yuelu District " , ParagraphAlignment.CENTER, 40 , false ));

                    // Table table second line 
                    firstXwpfTable.GetRow( 1 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Contact " , ParagraphAlignment.CENTER, 40 , true ));
                    firstXwpfTable.GetRow( 1 ).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " 小明同学" , ParagraphAlignment.CENTER, 40 , false ));
                    firstXwpfTable.GetRow( 1 ).GetCell( 2 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Contact " , ParagraphAlignment.CENTER, 40 , true ));
                    firstXwpfTable.GetRow( 1 ).GetCell( 3 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " 151****0456 " , ParagraphAlignment.CENTER, 40 , false ));


                    // Table table third line 
                    firstXwpfTable.GetRow( 2 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Enterprise License Number " , ParagraphAlignment.CENTER, 40 , true ));
                    firstXwpfTable.GetRow( 2 ).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " XXXXX-66666666 " , ParagraphAlignment.CENTER, 40 , false ));
                    firstXwpfTable.GetRow( 2 ).GetCell( 2 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " checks " , ParagraphAlignment.CENTER, 40 , true ));
                    firstXwpfTable.GetRow( 2 ).GetCell( 3 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, $ " Check this year 8 times " , ParagraphAlignment.CENTER, 40 , false ));


                    firstXwpfTable.GetRow( 3 ).MergeCells( 0 , 3 ); // Merge 3 columns 
                    firstXwpfTable.GetRow( 3 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, "" , ParagraphAlignment.LEFT, 10 , false ) );

                    #endregion

                    Var checkPeopleNum = 0 ; // Check the number of people 
                    var totalScore = 0 ; // Total score

                    #regionDocument The second table object instance (traversing the table item)
                     // Create a table object instance in the 
                    document XWPFTable secoedXwpfTable = document.CreateTable( 5 , 4 ); // Display the number of rows and columns rows: 8 rows, cols: 4 columns 
                    secoedXwpfTable.Width = 5200 ; // total width 
                    secoedXwpfTable.SetColumnWidth( 0 , 1300 ); /* set column width */ 
                    secoedXwpfTable.SetColumnWidth( 1 , 1100 ); /* set column width */ 
                    secoedXwpfTable.SetColumnWidth( 2, 1400 ); /* set column width * / 
                    secoedXwpfTable.SetColumnWidth ( 3 , 1400 ); / * set column width * /

                    / / Traverse the table title 
                    secoedXwpfTable.GetRow ( 0 ). GetCell ( 0 ). SetParagraph (SetTableParagraphInstanceSetting (document, firstXwpfTable, " employee name " , ParagraphAlignment.CENTER, 40 , true ));
                    secoedXwpfTable.GetRow( 0 ).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Gender " , ParagraphAlignment.CENTER, 40 , true ));
                    secoedXwpfTable.GetRow( 0 ).GetCell( 2 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " age " , ParagraphAlignment.CENTER, 40 , true ));
                    secoedXwpfTable.GetRow( 0 ).GetCell( 3 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Comprehensive Rating " , ParagraphAlignment.CENTER, 40 , true ));

                    / / Traverse four data 
                    for ( var i = 1 ; i < 5 ; i++ )
                    {
                        secoedXwpfTable.GetRow(i).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " 小明" + i + " 号" , ParagraphAlignment.CENTER, 40 , false ));
                        secoedXwpfTable.GetRow(i).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, " Men " , ParagraphAlignment.CENTER, 40 , false ));
                        secoedXwpfTable.GetRow(i).GetCell( 2 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, 20 + i + " Year " , ParagraphAlignment.CENTER, 40 , false ));
                        secoedXwpfTable.GetRow(i).GetCell( 3 ).SetParagraph(SetTableParagraphInstanceSetting(document, firstXwpfTable, 90 + i + " minute " , ParagraphAlignment.CENTER, 40 , false ));

                        checkPeopleNum ++ ;
                        totalScore += 90 + i;
                    }

                    #endregion

                    #regionDocument The third table object instance
                     // Create a table object instance in the 
                    document XWPFTable thirdXwpfTable = document.CreateTable( 5 , 4 ); // Display the number of rows and columns rows: 5 rows, cols: 4 columns 
                    thirdXwpfTable.Width = 5200 ; // total width 
                    thirdXwpfTable.SetColumnWidth ( 0 , 1300 ); / * set the column width * / 
                    thirdXwpfTable.SetColumnWidth ( . 1 , 1100 is ); / * set the column width * / 
                    thirdXwpfTable.SetColumnWidth ( 2 ,1400 ); / * set the column width * / 
                    thirdXwpfTable.SetColumnWidth ( 3 , 1400 ); / * set the column width * / / 
                    / Table table first row, the following merge 3 columns (note the row merge problem in the table, first merge, Post-fill content) 
                    thirdXwpfTable.GetRow( 0 ).MergeCells( 0 , 3 ); // From the first column, merge 3 columns 
                    thirdXwpfTable.GetRow( 0 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, " Check the content: " + 
                        $ "In the afternoon of {checkTime}, we checked the training of employees in the chasing time and made relevant statistics on the relevant information of the employees. The statistics are as follows:                                                                                                                                                                                                                 " +
                         " ------------------- -------------------------------------------------- ---------------- " + 
                        $ " A total of training for the company ({checkPeopleNum}), the total score of the training assessment is ({totalScore}) points. " + "" , ParagraphAlignment.LEFT, 30 , false ));


                    // Table table second line 
                    thirdXwpfTable.GetRow( 1 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, " Check result: " , ParagraphAlignment.CENTER, 40 , true ));
                    thirdXwpfTable.GetRow( 1 ).MergeCells( 1 , 3 ); // From the second column, merge three columns 
                    thirdXwpfTable.GetRow( 1 ).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, " The company is very good , insist on learning to punch every day, with vigorous vitality. " , ParagraphAlignment.LEFT, 40 , false ));

                    // Table table third line 
                    thirdXwpfTable.GetRow( 2 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, " Processing result: " , ParagraphAlignment.CENTER, 40 , true ));
                    thirdXwpfTable.GetRow( 2 ).MergeCells( 1 , 3 );
                    thirdXwpfTable.GetRow( 2 ).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, " Check by, score is excellent! " , ParagraphAlignment.LEFT, 40 , false ));

                    // The fourth row of the Table table, followed by the merge of 3 columns (note the row merge problem in the table, merge first, then fill the content), additional description 
                    thirdXwpfTable.GetRow( 3 ).MergeCells( 0 , 3 ); // merge 3 columns 
                    thirdXwpfTable.GetRow( 3 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, " Remarks: Remember, persistence is victory, always keep a kind of knowledge, good question! " , ParagraphAlignment.LEFT, 30 , False ));

                    // Table fifth line 
                    thirdXwpfTable.GetRow( 4 ).MergeCells( 0 , 1 );
                    thirdXwpfTable.GetRow( 4 ).GetCell( 0 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, "                                                                                                                                                                                                  Inspector Signature: Year Month Day " , ParagraphAlignment.LEFT, 40 , false ));
                    thirdXwpfTable.GetRow( 4 ).MergeCells( 1 , 2 );

                    thirdXwpfTable.GetRow( 4 ).GetCell( 1 ).SetParagraph(SetTableParagraphInstanceSetting(document, thirdXwpfTable, "                                                                                                                                                                                                  Enterprise Legal Person Signature: Year Month Day " , ParagraphAlignment.LEFT, 40 , false ));


                    #endregion

                    / / Write content to the document stream, generate word 
                    document.Write (stream);

                    savePath = " /SaveWordFile/ " + currentDate + " / " + fileName;

                    Return  true ;
                }
            }
            Catch (Exception ex)
            {
                // ignore 
                savePath = ex.Message;
                 return  false ;
            }
        }


        ///  <summary> 
        /// Create a paragraph object in a word document and set the basic style of the paragraph text (font size, font, font color, font alignment position)
         ///  </summary> 
        ///  <param name= "document"> document document object </param> 
        ///  <param name="fillContent"> The content of the first text object filled in the paragraph </param> 
        ///  <param name="isBold"> is bold < /param> 
        ///  <param name="fontSize"> Font Size </param> 
        ///  <param name="fontFamily"> Font </param> 
        ///  <param name="paragraphAlign"> Paragraph Arrangement ( Left aligned, centered, right aligned) </param>
        ///  <param name="isStatement">Whether to create a second text object in the same paragraph (to solve the problem of filling two or more text values ​​in the same paragraph, multiple texts need to be expanded by themselves, now support up to two) </param> 
        ///  <param name ="secondFillContent"> The content of the second declared text object is filled with the same style as the first time </param> 
        ///  <returns></returns> 
        private  static XWPFParagraph ParagraphInstanceSetting(XWPFDocument document, string fillContent, bool isBold , int fontSize, string fontFamily, ParagraphAlignment paragraphAlign, bool isStatement = false , string secondFillContent = "" )
        {
            XWPFParagraph paragraph = document.CreateParagraph(); // Create paragraph object 
            paragraph.Alignment = paragraphAlign; // Text display position, paragraph arrangement (left aligned, centered, right aligned) 

            XWPFRun xwpfRun = paragraph.CreateRun(); // Create paragraph Text object 
            xwpfRun.IsBold = isBold; // Text bold 
            xwpfRun.SetText(fillContent); // Fill content 
            xwpfRun.FontSize = fontSize; // Set the text size 
            xwpfRun.SetFontFamily(fontFamily, FontCharRange.None); // Set the title Styles such as: (Microsoft Yahei, Lishu, 楷 body) according to their own needs

            If (isStatement)
            {
                XWPFRun secondxwpfRun = paragraph.CreateRun(); // Create paragraph text object 
                secondxwpfRun.IsBold = isBold; // Text bold 
                secondxwpfRun.SetText(secondFillContent); // Fill content 
                secondxppfRun.FontSize = fontSize; // Set the text size 
                secondxwpfRun. SetFontFamily(fontFamily, FontCharRange.None); // Set the title style such as: (Microsoft
 Yahei, Lishu, 楷body) according to your needs             }


            Return paragraph;
        }

        ///  <summary>   
        /// Create a table paragraph instance in a Word document and set the basic style of the paragraph text of the form (font size, font, font color, font alignment position)
         ///  </summary>   
        ///  <param name ="document"> document document object </param>   
        ///  <param name="table"> table object </param>   
        ///  <param name="fillContent"> text to be filled </param>   
        // /  <param name="paragraphAlign"> Paragraph arrangement (left-aligned, centered, right-aligned) </param> 
        ///  <param name="rowsHeight"> Set the text position (set the line between the two lines), thus Implement the height setting effect of the table   </param> 
        ///  <param name="isBold">Whether it is bold (true bold, false is not bold) </param> 
        ///  <param name="fontSize"> font size</param> 
        ///  <returns></returns>   
        private  static XWPFParagraph SetTableParagraphInstanceSetting(XWPFDocument document, XWPFTable table, string fillContent, ParagraphAlignment paragraphAlign, int rowsHeight, bool isBold, int fontSize = 10 )
        {
            Var para = new CT_P();
            XWPFParagraph paragraph = new XWPFParagraph(para, table.Body); // Create a paragraph object in the table 
            paragraph.Alignment = paragraphAlign; // Text display position, paragraph arrangement (left aligned, centered, right aligned) 

            XWPFRun xwpfRun = paragraph.CreateRun (); / / create a paragraph text object 
            xwpfRun.SetText (fillContent);
            xwpfRun.FontSize = fontSize; / / font size 
            xwpfRun.IsBold = isBold; / / bold 
            xwpfRun.SetFontFamily ( " 宋体" , FontCharRange.None); / / set the font (such as: Microsoft Yahei, Chinese body, Song body) 
            xwpfRun.SetTextPosition(rowsHeight); // Set the text position (set the line between the two lines) to achieve the table height setting effect 
            return paragraph;
        }

        #endregion


    }
}

Summary:

At the end of the writing, I just want to say that I am too difficult. In order to realize the style I want, I will understand the paragraphs in NPOI and the basic attributes of the text by constantly checking the information. Eventually, when I generated the 22nd word, I finally achieved the effect I wanted. Here I will share some of the information I have read online and my own experience, I hope to help you, don’t forget to give me a star.

GitHub full sample address:
https://github.com/YSGStudyHards/NPOI-Export-Word

Orignal link:https://www.cnblogs.com/Can-daydayup/p/11588531.html