• NPOI实现word模板替换1


    using NPOI.XWPF.UserModel;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using System.Text;

    namespace WordExportDemo
    {
    /// <summary>
    /// npoi导出word
    /// </summary>
    public class DocHelper
    {

    /// <summary>
    ///
    /// </summary>
    /// <param name="model">实体数据</param>
    /// <param name="filepath">模板路径</param>
    /// <returns></returns>
    public static MemoryStream ExportDoc<T>(T model,string filepath)
    {
    using (FileStream stream = File.OpenRead(filepath))
    {
    XWPFDocument doc = new XWPFDocument(stream);
    //遍历段落
    foreach (var para in doc.Paragraphs)
    {
    ReplaceKey(model,para);
    }
    //遍历表格
    var tables = doc.Tables;
    foreach (var table in tables)
    {
    foreach (var row in table.Rows)
    {
    foreach (var cell in row.GetTableCells())
    {
    foreach (var para in cell.Paragraphs)
    {
    ReplaceKey(model,para);
    }
    }
    }
    }
    using (MemoryStream ms = new MemoryStream())
    {
    doc.Write(ms);
    return ms;
    }
    }

    }
    private static void ReplaceKey<T>(T entity,XWPFParagraph para)
    {

    try
    {
    Type entityType = typeof(T);
    PropertyInfo[] properties = entityType.GetProperties();
    string entityName = entityType.Name;
    string paratext = para.ParagraphText;
    var runs = para.Runs;
    string styleid = para.Style;
    string text = "";
    foreach (var run in runs)
    {
    text = run.ToString();
    foreach (var p in properties)
    {
    string propteryName = "$" + p.Name + "$";
    object value = p.GetValue(entity);
    if (value == null)
    {
    value = "";
    }
    if (text.Contains(propteryName))
    {
    text = text.Replace(propteryName, value.ToString());
    }
    run.SetText(text);
    }

    }
    }
    catch (Exception ex)
    {

    string msg = ex.Message + ex.StackTrace;
    }

    }
    }
    }

    本文来自博客园,作者:.net&new,转载请注明原文链接:https://www.cnblogs.com/wugh8726254/p/15306352.html

  • 相关阅读:
    微服务安全(二)OAuth 2.0
    微服务安全(一)
    Spring Security 学习+实践
    Dubbo 学习(二)服务注册与发现
    Dubbo 学习(一)
    Spring Cloud Hystrix 学习(三)请求合并
    Spring Cloud Hystrix 学习(二)熔断与降级
    Spring Cloud Hystrix 学习(一)
    Spring Cloud Gateway 学习+实践
    Spring Cloud Zuul 学习+实践
  • 原文地址:https://www.cnblogs.com/wugh8726254/p/15306352.html
Copyright © 2020-2023  润新知