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

  • 相关阅读:
    入门菜鸟
    FZU 1202
    XMU 1246
    Codeforces 294E Shaass the Great 树形dp
    Codeforces 773D Perishable Roads 最短路 (看题解)
    Codeforces 814E An unavoidable detour for home dp
    Codeforces 567E President and Roads 最短路 + tarjan求桥
    Codeforces 567F Mausoleum dp
    Codeforces 908G New Year and Original Order 数位dp
    Codeforces 813D Two Melodies dp
  • 原文地址:https://www.cnblogs.com/wugh8726254/p/15306352.html
Copyright © 2011-2022 走看看