首页 > 其他分享 >MiniWord .NET Word模板引擎,藉由Word模板和数据简单、快速生成文件。

MiniWord .NET Word模板引擎,藉由Word模板和数据简单、快速生成文件。

时间:2022-09-25 19:34:17浏览次数:183  
标签:Word Dictionary 藉由 SaveAsByTemplate value MiniWord new 模板 templatePath

Github / Gitee

QQ群(1群) : 813100564 / QQ群(2群) : 579033769

视频教学


介绍

MiniWord .NET Word模板引擎,藉由Word模板和数据简单、快速生成文件。

image

Getting Started

安装

快速入门

模板遵循“所见即所得”的设计,模板和标签的样式会被完全保留

var value = new Dictionary<string, object>(){["title"] = "Hello MiniWord"};
MiniSoftware.MiniWord.SaveAsByTemplate(outputPath, templatePath, value);

image

输入、输出

  • 输入系统支持模版路径或是Byte[]
  • 输出支持文件路径、Byte[]、Stream
SaveAsByTemplate(string path, string templatePath, Dictionary<string, object> value)
SaveAsByTemplate(string path, byte[] templateBytes, Dictionary<string, object> value)
SaveAsByTemplate(this Stream stream, string templatePath, Dictionary<string, object> value)
SaveAsByTemplate(this Stream stream, byte[] templateBytes, Dictionary<string, object> value)

标签

MiniWord 使用类似 Vue, React 的模版字串 {{tag}},只需要确保 tag 与 value 参数的 key 一样(大小写敏感),系统会自动替换字串。

文本

{{tag}}
代码例子
var value = new Dictionary<string, object>()
{
    ["Name"] = "Jack",
    ["Department"] = "IT Department",
    ["Purpose"] = "Shanghai site needs a new system to control HR system.",
    ["StartDate"] = DateTime.Parse("2022-09-07 08:30:00"),
    ["EndDate"] = DateTime.Parse("2022-09-15 15:30:00"),
    ["Approved"] = true,
    ["Total_Amount"] = 123456,
};
MiniWord.SaveAsByTemplate(path, templatePath, value);
模版

image

导出

image

图片

标签值为 MiniWordPicture 类别

代码例子
var value = new Dictionary<string, object>()
{
    ["Logo"] = new MiniWordPicture() { Path= PathHelper.GetFile("DemoLogo.png"), Width= 180, Height= 180 }
};
MiniWord.SaveAsByTemplate(path, templatePath, value);
模版

image

导出

image

列表

标签值为 string[] 或是 IList<string>类别

代码例子
var value = new Dictionary<string, object>()
{
    ["managers"] = new[] { "Jack" ,"Alan"},
    ["employees"] = new[] { "Mike" ,"Henry"},
};
MiniWord.SaveAsByTemplate(path, templatePath, value);
模版

image

导出

image

表格

标签值为 IEmerable<Dictionary<string,object>>类别

代码例子
var value = new Dictionary<string, object>()
{
    ["TripHs"] = new List<Dictionary<string, object>>
    {
        new Dictionary<string, object>
        {
            { "sDate",DateTime.Parse("2022-09-08 08:30:00")},
            { "eDate",DateTime.Parse("2022-09-08 15:00:00")},
            { "How","Discussion requirement part1"},
            { "Photo",new MiniWordPicture() { Path = PathHelper.GetFile("DemoExpenseMeeting02.png"), Width = 160, Height = 90 }},
        },
        new Dictionary<string, object>
        {
            { "sDate",DateTime.Parse("2022-09-09 08:30:00")},
            { "eDate",DateTime.Parse("2022-09-09 17:00:00")},
            { "How","Discussion requirement part2 and development"},
            { "Photo",new MiniWordPicture() { Path = PathHelper.GetFile("DemoExpenseMeeting01.png"), Width = 160, Height = 90 }},
        },
    }
};
MiniWord.SaveAsByTemplate(path, templatePath, value);
模版

image

导出

image

其他

POCO or dynamic 参数

v0.5.0 支持 POCO 或 dynamic parameter

var value = new { title = "Hello MiniWord" };
MiniWord.SaveAsByTemplate(outputPath, templatePath, value);

字体FontColor和HighlightColor

var value = new
{
    Company_Name = new MiniWordColorText { Text = "MiniSofteware", FontColor = "#eb70AB" },
    Name = new MiniWordColorText { Text = "Jack", HighlightColor = "#eb70AB" },
    CreateDate = new MiniWordColorText { Text = new DateTime(2021, 01, 01).ToString(), HighlightColor = "#eb70AB", FontColor = "#ffffff" },
    VIP = true,
    Points = 123,
    APP = "Demo APP",
};

我们可以尝试使用 MiniWodrHyperLink 类,用模板测试替换为超链接。

MiniWordHyperLink 提供了两个主要参数。

  • Url: HyperLink URI 目标路径
  • 文字:超链接文字
var value = new 
{
    ["Name"] = new MiniWordHyperLink(){
        Url = "https://google.com",
        Text = "測試連結!!"
    },
    ["Company_Name"] = "MiniSofteware",
    ["CreateDate"] = new DateTime(2021, 01, 01),
    ["VIP"] = true,
    ["Points"] = 123,
    ["APP"] = "Demo APP",
};
MiniWord.SaveAsByTemplate(path, templatePath, value);

例子

ASP.NET Core 3.1 API Export

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using MiniSoftware;

public class Program
{
    public static void Main(string[] args) => CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>());
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services) => services.AddMvc();
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseStaticFiles();
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=api}/{action=Index}/{id?}");
        });
    }
}

public class ApiController : Controller
{
    public IActionResult Index()
    {
        return new ContentResult
        {
            ContentType = "text/html",
            StatusCode = (int)HttpStatusCode.OK,
            Content = @"<html><body>
<a href='api/DownloadWordFromTemplatePath'>DownloadWordFromTemplatePath</a><br>
<a href='api/DownloadWordFromTemplateBytes'>DownloadWordFromTemplateBytes</a><br>
</body></html>"
        };
    }

    static Dictionary<string, object> defaultValue = new Dictionary<string, object>()
    {
        ["title"] = "FooCompany",
        ["managers"] = new List<Dictionary<string, object>> {
            new Dictionary<string, object>{{"name","Jack"},{ "department", "HR" } },
            new Dictionary<string, object> {{ "name", "Loan"},{ "department", "IT" } }
        },
        ["employees"] = new List<Dictionary<string, object>> {
            new Dictionary<string, object>{{ "name", "Wade" },{ "department", "HR" } },
            new Dictionary<string, object> {{ "name", "Felix" },{ "department", "HR" } },
            new Dictionary<string, object>{{ "name", "Eric" },{ "department", "IT" } },
            new Dictionary<string, object> {{ "name", "Keaton" },{ "department", "IT" } }
        }
    };

    public IActionResult DownloadWordFromTemplatePath()
    {
        string templatePath = "TestTemplateComplex.docx";

        Dictionary<string, object> value = defaultValue;

        MemoryStream memoryStream = new MemoryStream();
        MiniWord.SaveAsByTemplate(memoryStream, templatePath, value);
        memoryStream.Seek(0, SeekOrigin.Begin);
        return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        {
            FileDownloadName = "demo.docx"
        };
    }

    private static Dictionary<string, Byte[]> TemplateBytesCache = new Dictionary<string, byte[]>();

    static ApiController()
    {
        string templatePath = "TestTemplateComplex.docx";
        byte[] bytes = System.IO.File.ReadAllBytes(templatePath);
        TemplateBytesCache.Add(templatePath, bytes);
    }

    public IActionResult DownloadWordFromTemplateBytes()
    {
        byte[] bytes = TemplateBytesCache["TestTemplateComplex.docx"];

        Dictionary<string, object> value = defaultValue;

        MemoryStream memoryStream = new MemoryStream();
        MiniWord.SaveAsByTemplate(memoryStream, bytes, value);
        memoryStream.Seek(0, SeekOrigin.Begin);
        return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        {
            FileDownloadName = "demo.docx"
        };
    }
}

常见问题

模版字串没有生效

建议 {{tag}} 复制重新整串复制贴上,有时打字 word 在底层 {{}}会被切开变成<w:t>{</w:t><w:t>{<w:/t><w:t>Tag</w:t><w:t>}</w:t><w:t>}<w:/t> 如图片

image

标签:Word,Dictionary,藉由,SaveAsByTemplate,value,MiniWord,new,模板,templatePath
From: https://www.cnblogs.com/ITWeiHan/p/16728541.html

相关文章

  • An Image Worth 16x16 Words:Transformeers for Image Recognition At Scale | ViT 论
    参考https://www.bilibili.com/video/BV15P4y137jb/?spm_id_from=333.788&vd_source=920f8a63e92d345556c1e229d6ce363f李沐组会的ViT精读 ViT借用NLP领域的Transform......
  • SpringBoot集成onlyoffice实现word文档编辑保存
    说明onlyoffice为一款开源的office在线编辑组件,提供word/excel/ppt编辑保存操作以下操作均基于centos8系统,officeonly镜像版本7.1.2.23镜像下载地址:https://yunpan.360......
  • 模板方法模式 Template Method
    “组件协作”模式:现代软件专业分工之后的第一个结果是“框架与应用程序的划分”,“组件协作”模式通过晚期绑定,来实现框架与应用程序之间的松耦合,是二者之间协作时常用的......
  • Stop Learning English Words by ROTE - guner
    英语单词的最高境界就是不背单词/?来自一本魔性的书,书的作者自称“枪哥”虽然slogan是这样但是实际上书中介绍了一些有关于单词和中文的区别与类同用词根词缀的方式去演......
  • leetcode python 解题模板
    一般的题classSolution(object):defletterCombinations(self,digits):""":typedigits:str:rtype:List[str]"""......
  • Liunx环境变量配置模板
    目录jdk环境jdk环境vim/etc/profileexportJAVA_HOME=/opt/javaexportJRE_HOME=$JAVA_HOME/jreexportCLASSPATH=$JAVA_HOME/lib:$JRE_HOME/lib:$CLASSPATHexport......
  • 安装项目模板IdentityServer4.Templates
    打开PowseShell执行以下命令dotnetnew-iIdentityServer4.Templates  ......
  • 二分查找模板
    //arr数组升序//n是数组长度,也就是lr正好是数组的左右的第一个和最后一个intl=0,r=n-1;intmid;while(l<=r){mid=(l+r)/2;if(arr[mid]==......
  • 字符串模板汇总
    字符串模板KMP#include<iostream>#include<cstring>#include<cstdio>usingnamespacestd;constintMAXN=1000010;intn,m,next[MAXN];chara[MAXN],b[MAXN]; ......
  • variadic templates (数量不定的模板参数)
    voidprint(){}//当只剩下一个参数时,args为空,执行这个版本的printtemplate<typenameT,typename...Types>voidprint(constT&firstArg,constTypes&...args){......