zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    二、Elasticsearch核心配置文件详解
    javax.mail.AuthenticationFailedException: 535 authentication failed
    Java compiler level does not match the version of the installed java project facet
    一、设置cookie报非法参数异常
    slf4j的使用规范
    基于token的身份验证JWT
    单点登录
    spring的bean不能注入原因分析
    规避空指针异常规范
    Git远程操作详解
  • 原文地址:https://www.cnblogs.com/wugh8726254/p/15306352.html
Copyright © 2011-2022 走看看