asp.net core 用NPOI放word中写入数据

 

 

第一步:引入NPOI程序包

 

 

 

第二步:准备好要插入数据的word模板

 

 

第三步:读取数据写入word中,注意对象名和word中的名一致,而且word中的名不能重复,否则写入不上,代码不用考虑word排版样式的问题

  1 using Microsoft.AspNetCore.Hosting;
  2 using Microsoft.AspNetCore.Mvc;
  3 using Microsoft.Extensions.Logging;
  4 using NPOI.XWPF.UserModel;
  5 using Sswl.Interfaces.IService;
  6 using Sswl.Model;
  7 using SswlSub.Controllers.Basic;
  8 using SswlSub.Extensions;
  9 using Swashbuckle.AspNetCore.Annotations;
 10 using System;
 11 using System.IO;
 12 using System.Linq;
 13 using System.Reflection;
 14 using System.Threading.Tasks;
 15 
 16 namespace SswlSub.Controllers.Business
 17 {
 18     [SwaggerTag("合同下载")]
 19     [ApiExplorerSettings(GroupName = "public")]
 20     public class ExportController : BaseController
 21     {
 22         private readonly TokenManager _tokenManager;
 23         private readonly IContractService _contractService;
 24         private readonly IWebHostEnvironment _hostEnvironment;
 25         private readonly ILogger<ExportController> _logger;
 26         private readonly IEnterpriseInfoService _enterpriseInfoService;
 27 
 28         public ExportController(TokenManager tokenManager, IContractService contractService, IWebHostEnvironment hostEnvironment, ILogger<ExportController> logger, IEnterpriseInfoService enterpriseInfoService)
 29         {
 30             _tokenManager = tokenManager;
 31             _contractService = contractService;
 32             _hostEnvironment = hostEnvironment;
 33             _enterpriseInfoService = enterpriseInfoService;
 34             _logger = logger;
 35         }
 36 
 37 
 38         [HttpPost]
 39         public async Task<IActionResult> GetWord(int id)
 40         {
 41             try
 42             {
 43                 //var b =  _hostEnvironment.ContentRootPath;
 44                 //string[] pa = b.Split('\\');
 45                 string fileName = "/home/data/app/sswlsub/word/hetong.docx";
 46                 //var c = pa[0] + "\\" + pa[1] + "\\" + pa[2] + "\\" + "wwwroot";
 47                 //string fileName = Path.Combine(b, "hetong.docx");
 48                 XWPFDocument workbook = null;
 49                 using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
 50                 {
 51                     workbook = new XWPFDocument(fileStream);
 52                 }
 53                 if (workbook == null)
 54                 {
 55                     _logger.LogInformation("没有读取到文件");
 56                 }
 57 
 58                 var result = await _contractService.GetDB().Queryable<Contract>().Where(a => a.ContractId == id).FirstAsync();
 59                 if (result != null)
 60                 {
 61                     var entInfos = Sswl.Configs.MiddlemanConfig.middlemanConfigs.MiddlemanEntInfos;
 62                     var middlean = entInfos.Where(a => a.EnterpriseId == result.MiddlemanId).FirstOrDefault();
 63                     var carrier = await _enterpriseInfoService.GetDB().Queryable<EnterpriseInfo>().Where(a => a.EnterpriseInfoId == result.CarrierId && a.IsDel==false).FirstAsync();
 64                     var sum = "";
 65                     var money = "";
 66                     if (result.TotaTon >= 10000)
 67                     {
 68                         sum = (result.TotaTon / 10000).ToString().TrimEnd('0').TrimEnd('.') + "万吨";
 69                     }
 70                     else
 71                     {
 72                         sum = (result.TotaTon).ToString().TrimEnd('0').TrimEnd('.') + "";
 73                     }
 74                     if (result.Deposit >= 10000)
 75                     {
 76                         money = (result.Deposit / 10000).ToString().TrimEnd('0').TrimEnd('.') + "万元";
 77                     }
 78                     else
 79                     {
 80                         money = (result.Deposit).ToString().TrimEnd('0').TrimEnd('.') + "";
 81                     }
 82 
 83 
 84                     var word = new
 85                     {
 86                         goods = result.ContractName,
 87                         jiafang = middlean != null ? middlean.EnterpriseName : "",
 88                         bian = result.ContractNo,
 89                         yifang = result.CarrierName,
 90                         qiandingdizhi = result.SignAddress,
 91                         //qiandingtime = result.SignDate.Value.ToLongDateString().ToString(),
 92                         //qiandingtime = string.Format("{0:D}", result.SignDate),
 93                         //qiandingtime = result.SignDate.Value.GetDateTimeFormats('d')[0].ToString(),
 94                         qiandingtime = result.SignDate.Value.ToString("yyyy年M月d日"),
 95                         sg = sum + result.GoodsName,
 96                         kyear = result.BeginDate.Value.Year,
 97                         kmonth = result.BeginDate.Value.Month,
 98                         kday = result.BeginDate.Value.Day,
 99                         eyear = result.EndDate.Value.Year,
100                         emonth = result.EndDate.Value.Month,
101                         eday = result.EndDate.Value.Day,
102                         money = money,
103                         shui = result.TaxRate + "%"
104                     };
105 
106 
107                     var wordtable = new
108                     {
109                         goodsname = result.GoodsName,
110                         zhuangaddress = result.LoadingAddressName,
111                         xieaddress = result.UnloadingAddressName,
112                         maxnumber = result.DayMaxTon.ToString().TrimEnd('0').TrimEnd('.'),
113                         yunju = result.Distance.ToString().TrimEnd('0').TrimEnd('.'),
114                         danjia = result.FreightPrice.ToString().TrimEnd('0').TrimEnd('.'),
115                         shuilv = result.TaxRate + "%",
116                         jf = middlean != null ? middlean.EnterpriseName : "",
117                         yf = carrier != null ? carrier.EnterpriseName : "",
118                         adress = middlean != null ? middlean.RegAddress : "",
119                         faren = middlean != null ? middlean.LegalPerson : "",
120                         phone = middlean != null ? middlean.RegMobile : "",
121                         bank = middlean != null ? middlean.BankName : "",
122                         card = middlean != null ? middlean.BankCardNo : "",
123                         etax = middlean != null ? middlean.TaxCode : "",
124                         dz = carrier != null ? carrier.RegAddress : "",
125                         fm = carrier != null ? carrier.LegalPerson : "",
126                         dianhao = carrier != null ? carrier.RegMobile : "",
127                         kaihuhang = carrier != null ? carrier.BankName : "",
128                         zangha = carrier != null ? carrier.BankCardNo : "",
129                         shuhp = carrier != null ? carrier.TaxCode : ""
130                     };
131 
132                     foreach (var para in workbook.Paragraphs)
133                     {
134                         ReplaceKey(para, word);
135                     }
136                     //遍历表格      
137                     var tables = workbook.Tables;
138                     foreach (var table in tables)
139                     {
140                         foreach (var row in table.Rows)
141                         {
142                             foreach (var cell in row.GetTableCells())
143                             {
144                                 foreach (var para in cell.Paragraphs)
145                                 {
146                                     ReplaceKey(para, wordtable);
147                                 }
148                             }
149                         }
150                     }
151 
152                 }
153                 MemoryStream ms = new MemoryStream();
154                 workbook.Write(ms);
155                 byte[] bytefile = ms.ToArray();
156                 var filename = $"{DateTime.Now:yyyyMMddHHmmssffff}.docx";
157                 return File(bytefile, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename);
158             }
159             catch (Exception ex)
160             {
161                 _logger.LogError("导出excel失败", ex);
162                 return null;
163             }
164         }
165 
166 
167         private static void ReplaceKey(XWPFParagraph para, object model)
168         {
169             string text = para.ParagraphText;
170             var runs = para.Runs;
171             string styleid = para.Style;
172             for (int i = 0; i < runs.Count; i++)
173             {
174                 var run = runs[i];
175                 text = run.ToString();
176                 Type t = model.GetType();
177                 PropertyInfo[] pi = t.GetProperties();
178                 foreach (PropertyInfo p in pi)
179                 {
180                     //文档中替换${Name}
181                     if (text.Contains("" + p.Name + ""))
182                     {
183                         text = text.Replace("" + p.Name + "", p.GetValue(model, null).ToString());
184                     }
185                 }
186                 runs[i].SetText(text, 0);
187             }
188             //string text = para.ParagraphText;
189             //Type t = model.GetType();
190             //PropertyInfo[] pi = t.GetProperties();
191             //foreach (PropertyInfo p in pi)
192             //{
193             //    文档中替换${ Name}
194             //    if (text.Contains("${" + p.Name + "}$"))
195             //    {
196             //        text = text.Replace("${" + p.Name + "}$", p.GetValue(model, null).ToString());
197             //    }
198             //}
199             //para.set
200         }
201     }
202 }
读取数据写入

 

WIN-LEC4OGJB34R

 

posted @ 2022-01-26 17:08  江南-烟雨  阅读(508)  评论(0编辑  收藏  举报