引用库:FreeSpire.Doc
using Spire.Doc; using Spire.Doc.Documents; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Web; namespace YFAPICommon.Libs { public class WordTool { public static void writeWordFile<T>(T neirongData,string title,string path) { //创建文档 Document doc = new Document(); //标题落样式 ParagraphStyle style1 = new ParagraphStyle(doc); style1.Name = "titleStyle"; style1.CharacterFormat.Bold = true; //style1.CharacterFormat.TextColor = Color.Purple; style1.CharacterFormat.FontName = "宋体"; style1.CharacterFormat.FontSize = 18; doc.Styles.Add(style1); //字段名段落样式 ParagraphStyle style2 = new ParagraphStyle(doc); style2.Name = "zhutiStyle"; style2.CharacterFormat.FontName = "宋体"; style2.CharacterFormat.FontSize = 13; style2.CharacterFormat.Bold = true; doc.Styles.Add(style2); //字段内容段落样式 ParagraphStyle style3 = new ParagraphStyle(doc); style3.Name = "neirongStyle"; style3.CharacterFormat.FontName = "宋体"; style3.CharacterFormat.FontSize = 11; doc.Styles.Add(style3); //添加section Section s = doc.AddSection(); //添加标题 Paragraph para1 = s.AddParagraph(); para1.AppendText(title); para1.ApplyStyle("titleStyle"); //设置段落对齐方式 para1.Format.HorizontalAlignment = HorizontalAlignment.Center; //设置段落缩进 para1.Format.AfterSpacing = 15; //遍历neirongData对象字段内容 PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); object[] values = new object[properties.Count]; for (int j = 0; j < values.Length; j++) { var col = properties[j].Name;//字段名 object obj = properties[j].GetValue(neirongData); var str = obj == null ? "" : obj.ToString();//字段内容 //字段名 Paragraph zhuti = s.AddParagraph(); zhuti.AppendText(col); zhuti.Format.HorizontalAlignment = HorizontalAlignment.Justify; zhuti.ApplyStyle("zhutiStyle"); zhuti.Format.FirstLineIndent = 10; zhuti.Format.AfterSpacing = 15; //字段内容 Paragraph neirong = s.AddParagraph(); neirong.AppendText(str); neirong.Format.HorizontalAlignment = HorizontalAlignment.Justify; neirong.ApplyStyle("neirongStyle"); neirong.Format.FirstLineIndent = 10; neirong.Format.AfterSpacing = 15; } //保存文档 doc.SaveToFile(path, FileFormat.Docx2013); } } }
调用
public ReturnNode exportToWord(BaseAdminDetailInput input) { var doc = (from p in dbContext.Project.Where(u => u.id == input.id) select new { 项目名称 = p.mingcheng, 项目状态 = p.zhuangtai, 项目内容 = p.neirong, 项目类型 = p.leixing, 添加时间 = p.createTime }).FirstOrDefault(); string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".docx"; string file = localPath + fileName; WordTool.writeWordFile(doc,doc.项目名称, file); return ReturnNode.ReturnSuccess(serverPath+ fileName); }