swagger文档转Word

引用包
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.2.3" />
<PackageReference Include="AiSY-Yang.ExtensionMethods.AspNetCore" Version="1.0.4" />
<PackageReference Include="NPOI" Version="2.5.5" />
<PackageReference Include="NSwag.Core" Version="13.15.5" />
添加如下控制器
请求对应地址即可

点击查看代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

using ExtensionMethods;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

using NPOI.XWPF.UserModel;

using NSwag;

using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace Web.Controllers
{
	[AllowAnonymous]
	public class SwaggerController : Controller
	{
		private readonly ISwaggerProvider swagger;
		private readonly SwaggerGeneratorOptions generatorOptions;

		public SwaggerController(ISwaggerProvider swagger, SwaggerGeneratorOptions generatorOptions)
		{
			this.swagger = swagger;
			this.generatorOptions = generatorOptions;
		}
		/// <summary>
		/// 读取对应swagger文档的Word文档
		/// </summary>
		/// <param name="documentName">swagger文档名</param>
		/// <returns>Word文档</returns>
		[HttpGet("[controller]/[action]")]
		public IActionResult Word(string documentName)
		{
			if (generatorOptions.SwaggerDocs.ContainsKey(documentName))
			{
				Uri uri = new System.Uri("http://127.0.0.1:" + HttpContext.Connection.LocalPort.ToString() + "/swagger/" + documentName + "/swagger.json");
				Stream stream = OpenApiToWord.Parse(uri);
				stream.Position = 0;
				return File(stream, Tools.GetMIME(".docx"), $"{documentName}.docx");
			}
			else
			{
				return NoContent();
			}
		}
	}
	/// <summary>
	/// OpenApi文档转化为Word
	/// </summary>
	public static class OpenApiToWord
	{
		public static MemoryStream Parse(string json)
		{
			OpenApiDocument document = OpenApiDocument.FromJsonAsync(json).Result;
			return Parse(document);
		}
		public static MemoryStream Parse(Uri uri)
		{
			OpenApiDocument document = OpenApiDocument.FromUrlAsync(uri.ToString()).Result;
			return Parse(document);
		}
		public static MemoryStream Parse(FileInfo file)
		{
			OpenApiDocument document = OpenApiDocument.FromFileAsync(file.FullName).Result;
			return Parse(document);
		}
		public static MemoryStream Parse(OpenApiDocument document)
		{
			XWPFDocument doc = new XWPFDocument();
			foreach (var path in document.Paths)
			{
				foreach (var method in path.Value.ActualPathItem)
				{
					doc.CreateParagraph().CreateRun().SetText($"接口描述:{method.Value.Summary}");
					doc.CreateParagraph().CreateRun().SetText($"接口地址:{path.Key}");
					doc.CreateParagraph().CreateRun().SetText($"请求方法:{method.Key}");
					doc.CreateParagraph().CreateRun().SetText($"请求参数:");
					WritePara(method.Value.Parameters);
					doc.CreateParagraph().CreateRun().SetText($"响应结果:");
					WriteRes(method.Value.ActualResponses);
				}
				doc.CreateParagraph().CreateRun().SetText($"");
			}

			MemoryStream out1 = new MemoryStream();
			doc.Write(out1);
			return new MemoryStream(out1.ToArray());

			void WritePara(IList<OpenApiParameter> parameters)
			{
				var parametersTable = doc.CreateTable();
				XWPFTableRow head = parametersTable.GetRow(0);
				head.GetCell(0).SetText("参数名");
				head.CreateCell().SetText("参数类型");
				head.CreateCell().SetText("参数格式");
				head.CreateCell().SetText("参数位置");
				head.CreateCell().SetText("能否为空");
				head.CreateCell().SetText("参数描述");
				foreach (var item in parameters)
				{
					if (item.ActualSchema.Type == NJsonSchema.JsonObjectType.Object)
					{
						WriteObject(item.ActualSchema, item.Kind.ToString());
					}
					else
					{
						XWPFTableRow row = parametersTable.CreateRow();
						row.GetCell(0).SetText(item.Name);
						row.GetCell(1).SetText(item.ActualSchema.Type.ToString());
						row.GetCell(2).SetText(item.ActualSchema.Format);
						row.GetCell(3).SetText(item.Kind.ToString());
						row.GetCell(4).SetText(item.IsNullableRaw.ToString());
						row.GetCell(5).SetText(item.Description);
					}
				}
				void WriteObject(NJsonSchema.JsonSchema schema, string location)
				{
					foreach (var propertie in schema.Properties)
					{
						XWPFTableRow row = parametersTable.CreateRow();
						row.GetCell(0).SetText(propertie.Value.Name);
						row.GetCell(1).SetText(propertie.Value.ActualSchema.Type.ToString());
						row.GetCell(2).SetText(propertie.Value.ActualSchema.Format);
						row.GetCell(3).SetText(location);
						row.GetCell(4).SetText(propertie.Value.IsNullableRaw.ToString());
						row.GetCell(5).SetText(propertie.Value.Description);
						switch (propertie.Value.Type)
						{
							case NJsonSchema.JsonObjectType.Array:
								WriteObject(propertie.Value.Item.ActualSchema, location);
								break;
							case NJsonSchema.JsonObjectType.Object:
								WriteObject(propertie.Value, location);
								break;
							case NJsonSchema.JsonObjectType.None:
							case NJsonSchema.JsonObjectType.Boolean:
							case NJsonSchema.JsonObjectType.Integer:
							case NJsonSchema.JsonObjectType.Null:
							case NJsonSchema.JsonObjectType.Number:
							case NJsonSchema.JsonObjectType.String:
							case NJsonSchema.JsonObjectType.File:
								break;
							default:
								break;
						}
					}
				}
			}
			void WriteRes(IReadOnlyDictionary<string, OpenApiResponse> Responses)
			{
				foreach (var response in Responses)
				{
					doc.CreateParagraph().CreateRun().SetText($"{response.Key}:{response.Value.Description}");
					if (response.Value.Schema == null)
					{
						continue;
					}
					//直接返回literal
					if (response.Value.Schema.ActualSchema.Properties.Count == 0)
					{
						doc.CreateParagraph().CreateRun().SetText($"\t结果类型:{response.Value.Schema.ActualSchema.ActualSchema.Type}");
						doc.CreateParagraph().CreateRun().SetText($"\t结果格式:{response.Value.Schema.ActualSchema.ActualSchema.Format}");
						doc.CreateParagraph().CreateRun().SetText($"\t能否为空:{response.Value.Schema.ActualSchema.ActualSchema.IsNullableRaw}");
						//XWPFTableRow row = resopnseTable.CreateRow();
						//row.GetCell(0).SetText(response.Value.Schema.ActualSchema.Description);
						//row.GetCell(1).SetText(response.Value.Schema.ActualSchema.ActualSchema.Type.ToString());
						//row.GetCell(2).SetText(response.Value.Schema.ActualSchema.ActualSchema.Format);
						//row.GetCell(3).SetText(response.Value.Schema.ActualSchema.IsNullableRaw.ToString());
						//row.GetCell(4).SetText(response.Value.Schema.ActualSchema.Description);
						continue;
					}
					var resopnseTable = doc.CreateTable();
					XWPFTableRow head = resopnseTable.GetRow(0);
					head.GetCell(0).SetText("字段名");
					head.CreateCell().SetText("字段类型");
					head.CreateCell().SetText("字段格式");
					head.CreateCell().SetText("能否为空");
					head.CreateCell().SetText("字段描述");
					WriteObject(response.Value.Schema.ActualSchema);
					void WriteObject(NJsonSchema.JsonSchema schema)
					{
						//包装在class内返回
						foreach (var propertie in schema.Properties)
						{
							XWPFTableRow row = resopnseTable.CreateRow();
							row.GetCell(0).SetText(propertie.Value.Name);
							row.GetCell(1).SetText(propertie.Value.ActualSchema.Type.ToString());
							row.GetCell(2).SetText(propertie.Value.ActualSchema.Format);
							row.GetCell(3).SetText(propertie.Value.IsNullableRaw.ToString());
							row.GetCell(4).SetText(propertie.Value.Description);
							switch (propertie.Value.Type)
							{
								case NJsonSchema.JsonObjectType.Array:
									WriteObject(propertie.Value.Item.ActualSchema);
									break;
								case NJsonSchema.JsonObjectType.Object:
									WriteObject(propertie.Value);
									break;
								case NJsonSchema.JsonObjectType.None:
								case NJsonSchema.JsonObjectType.Boolean:
								case NJsonSchema.JsonObjectType.Integer:
								case NJsonSchema.JsonObjectType.Null:
								case NJsonSchema.JsonObjectType.Number:
								case NJsonSchema.JsonObjectType.String:
								case NJsonSchema.JsonObjectType.File:
									break;
								default:
									break;
							}
						}
					}
				}
			}
		}
	}
}

上一篇:Excel 如何间隔N行取数


下一篇:《DDIA》读书笔记:复制(1)