Because you haven't touched NPOI before, almost all of them are learning while Baidu fumbles.
This plugin is very convenient for data import and export of Excel.
But for exporting word documents, it can be said that it is very few, Baidu has a lot of.... Also, I don't stop trying the code, so I sorted out some of my own opinions to record the code.
Say nothing more, code it...
With this plugin you need to prepare:
Front-end code: Relatively, knowing how to write ajax is fine
$.ajax({ type: "POST", url: "@Url.Action("SaveWordFile")?id=" + id, data: JSON, success: function (data) { console.log("Return information:" + data); if (data != "false") { alert("Generate file successful!"); window.location.href = data;//File path to data } else { alert("Failed to generate file!"); } }, error: function () { alert("File generation error!"); } });
What matters is the back-end code:
//export Work #region generate word /// <summary> /// generate word File,And save the static resource folder ( wwwroot)Lower SaveWordFile In folder /// </summary> /// <param name="savePath">Save Path</param> public async Task<string> SaveWordFile(string savePath, string id) { //according to id Find the selected information for this item var Date_SecurityWorkPolicyTarget = await _context.SecurityWorkPolicyTarget.FirstOrDefaultAsync(m => m.Id == id); savePath = ""; try { string currentDate = DateTime.Now.ToString("yyyyMMdd"); //Save file to static resource wwwroot,Using absolute path paths var uploadPath = _environment.WebRootPath + "/SaveWordFile/" + currentDate + "/";//>>>Amount to HttpContext.Current.Server.MapPath("") //Title of stitching file: just stitch the data you need string workFileName = Date_SecurityWorkPolicyTarget.SubordinateCompany + "file"; string fileName = string.Format("{0}.docx", workFileName, System.Text.Encoding.UTF8); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } //By using file streams, create file stream objects, write to the file stream, and save as Word Document Format using (var stream = new FileStream(Path.Combine(uploadPath, fileName), FileMode.Create, FileAccess.Write)) { //Establish document Document object instance XWPFDocument document = new XWPFDocument(); /** *This reduces code redundancy by setting SetParagraph instance creation and paragraph style formatting in a common Word document. * Avoid creating a paragraph implementation instance and setting the basic style of the paragraph every time a paragraph is used *(As follows, Paragraph InstanceSetting creates and style settings for paragraph implementations, followed by an index indicating the current row of paragraphs, starting with 0) */ //Text Title document.SetParagraph(ParagraphInstanceSetting(document, workFileName, true, 28, "Song Style", "#ff0000", UnderlinePatterns.None, ParagraphAlignment.CENTER), 0); //TODO:This line needs to display two pieces of text //document.SetParagraph(ParagraphInstanceSetting(document, $"[Send Number)", false, 14, "Song Style", ParagraphAlignment.CENTER, true, $" Check time:{checkTime}"), 1); //This line shows a text or fills in variables that need to be filled in document.SetParagraph(ParagraphInstanceSetting(document, Date_SecurityWorkPolicyTarget.DocumentNumber, false, 14, "Song Style", "", UnderlinePatterns.None, ParagraphAlignment.CENTER), 1);
//Writes to the document stream, generates word(File Input Stream for short) document.Write(stream); savePath = "/SaveWordFile/" + currentDate + "/" + fileName;//Generate files to paths you need to save: Stitch paths yourself //Return path to foreground return savePath; } catch (Exception ex) { //ignore savePath = ex.Message; return "false"; } }
Basic style settings for word documents:
This is the basic style parameter, just use it as you need it.. If there is no such thing, I suggest Baidu, I only checked what I used.
/// <summary> /// Establish word Paragraph objects in documents and basic styles for setting paragraph text (font size, font, font color, font alignment position) /// </summary> /// <param name="document">document Document object</param> /// <param name="fillContent">The content that the first text object of the paragraph fills</param> /// <param name="isBold">Bold or not</param> /// <param name="fontSize">font size</param> /// <param name="fontFamily">Typeface</param> /// <param name="paragraphAlign">Paragraph alignment (left, center, right)</param> /// <param name="isStatement">Whether to create a second text object in the same paragraph (to solve the case where two or more text values need to be filled in the same paragraph, multiple text needs to be expanded by itself, and now supports up to two)</param> /// <param name="secondFillContent">The second declared text object fills in the same style as the first</param> /// <returns></returns> private static XWPFParagraph ParagraphInstanceSetting(XWPFDocument document, string fillContent, bool isBold, int fontSize, string fontFamily, string rgbStr, UnderlinePatterns value, ParagraphAlignment paragraphAlign, bool isStatement = false, string secondFillContent = "") { XWPFParagraph paragraph = document.CreateParagraph();//Create Paragraph Object paragraph.Alignment = paragraphAlign;//Text Display Position,Paragraph alignment (left, center, right) XWPFRun xwpfRun = paragraph.CreateRun();//Create Paragraph Text Object xwpfRun.IsBold = isBold;//font-weight xwpfRun.SetText(fillContent);//Fill in content xwpfRun.FontSize = fontSize;//Set text size xwpfRun.SetFontFamily(fontFamily, FontCharRange.None); //Set the title style such as: (Microsoft Yahei, Lishu, Kai Title) according to your needs xwpfRun.SetColor(rgbStr);//Set Font Color--Hexadecimal xwpfRun.SetUnderline(value);//Set Underline, Enumerate Types //Style of the second text if (isStatement) { XWPFRun secondxwpfRun = paragraph.CreateRun();//Create Paragraph Text Object secondxwpfRun.IsBold = isBold;//font-weight secondxwpfRun.SetText(secondFillContent);//Fill in content secondxwpfRun.FontSize = fontSize;//Set text size secondxwpfRun.SetFontFamily(fontFamily, FontCharRange.None); //Set the title style such as: (Microsoft Yahei, Lishu, Kai Title) according to your needs } return paragraph; }
The result of the last word document exported is:
I mainly use paragraphs, line by line, so that's what it does...
Suggestions for word typesetting: Leaders say they need some line breaks.... Etc.
It is recommended that the data be stored in a row-by-row format so that the data can be exported after being manipulated in the background, so that the exported line-by-line format is what you need...
Line break conversion is a good thing
string[] strArr_FG = Date_SecurityWorkPolicyTarget.Filecontent.Split("\r\n");//according to xx Delimited String
This gives you an array of line breaks...
The next step is to look at the business and demand...
Summary: I spent two days to do this code requirement from contacting this plug-in. Actually, the plug-ins all know how to use it and have not been studied in depth, but learning some new code is also a kind of progress. The accumulation is not overnight, Rome was not built in a day, but after all, all roads lead to Rome, persistent learning is the best.
Others need word table format, so don't put code on them.
Give me a link to the reference code and I think the author wrote it well.
https://www.cnblogs.com/Can-daydayup/p/11588531.html#_label1