Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions OfficeScript/ExcelToCSV.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Excel方眼紙をcsvに変換するOfficeスクリプトです。想定するExcelファイルはSample.xlsxをご確認ください。
function main(workbook: ExcelScript.Workbook) {
// アクティブなワークシートを取得します
const sheet = workbook.getActiveWorksheet();

// シートの範囲を取得します
const range = sheet.getUsedRange();
const values = range.getValues();

// "No"という値が初めて現れる行のインデックスを特定する
let startRowIndex = -1;
for (let i = 0; i < values.length; i++) {
if (values[i].includes("No")) {
startRowIndex = i;
break;
}
}

if (startRowIndex === -1) {
console.log("Noが見つかりませんでした。");
return;
}

// CSVとして保存する文字列を作成します
let csvContent = "";

// "No"が出現する行から始まる行を走査し、コンマで区切られた文字列に変換します
for (let i = startRowIndex; i < values.length; i++) {
// 空白や無効なエントリをフィルタリング
const processedRow = values[i].filter(cell => cell != null && cell !== '');

// コンマの連続を取り除く
let row = processedRow.join(",").replace(/,{2,}/g, ','); // 連続するコンマを1つに置換

// 行がカンマだけでない場合のみ追加
if (row.replace(/,/g, '').trim() !== '') {
csvContent += row + "\r\n"; // 改行コードを追加
}
}

// 結果をログに出力します。
console.log(csvContent);

}
69 changes: 69 additions & 0 deletions Python/Sample.xlsx.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
openapi: 3.0.0
info:
title: API Documentation
version: 1.0.0
paths:
example_endpoint:
post:
summary: Sample
description: どう取得するか保留
operationId: example_operationId
responses:
'200':
description: レスポンスの説明をどう取得するか保留
content:
application/json;charset=utf-8:
schema:
type: object
properties:
result-code:
type: string
description: システム作成のコード
example: R0000000
result-message:
type: string
description: システム生成のメッセージ
example: リクエスト完了
user-id:
type: string
description: ユーザーID
user-info:
type: list
description: ユーザーの所属情報を格納するリスト
affiliation-code:
type: string
description: 所属を表すコード
affiliation-name:
type: string
description: 所属名
user-name:
type: string
description: ユーザー氏名
user-birth:
type: string
description: ユーザー生年月日
user-phone-number:
type: string
description: ユーザー電話番号
required:
- result-code
- result-message
- user-id
- user-info
- affiliation-code
- affiliation-name
- user-name
- user-phone-number
requestBody:
description: 未定
required:
- user-id
content:
application/json;charset=utf-8:
schema:
type: object
properties:
user-id:
type: string
description: ユーザーID
example: XXXXX
101 changes: 101 additions & 0 deletions Python/exchange_csv_to_json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import csv
import json

# 入力CSVファイルのパス
input_csv = 'input.csv'

# OpenAPI仕様の初期テンプレート
oas_template = {
"openapi": "3.0.0",
"info": {
"title": "API Document",
"version": "1.0.0"
},
"paths": {},
"components": {
"schemas": {}
}
}

def nest_schema(hierarchy, current_level, properties):
if not hierarchy:
return properties

next_level = hierarchy.pop(0)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[質問] hierarchyはどんな変数ですか?ドキュメンテーションを行うことで回答に代えてもよいです。

if next_level not in current_level:
current_level[next_level] = {
"type": "object",
"properties": {}
}

current_level[next_level]["properties"].update(properties)
return current_level
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[任意]current_levelがdictなら、参照渡しになるので、in-placeでアップデートする関数であるとした方が私は好みだな


# CSVファイルの読み取り
with open(input_csv, mode='r', encoding='utf-8') as file:
reader = csv.DictReader(file)
components_schemas = {}
path_specs = {
"/examplePath": {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[必須]パス名を変更できるようにしてください
[必須]複数のパス名とメソッドの組を定義してください

"get": {
"summary": "Example summary",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[必須]operationIdを記載してください。CSVカラムも追加してください。

"responses": {
"200": {
"description": "A successful response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Response"
}
}
},
"headers": {}
}
}
}
}
}
response_properties = {}
hierarchy_map = {}

for row in reader:
hierarchy = row['階層'].split('.')
if row['項目(英名)'] == 'Content-Type':
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[推奨]カラム「種別区分」を適切に使用して処理をしていただきたいです
[推奨]Content-Typeはヘッダには定義しないでいただきたいです。仕様上は合っていますが、それを含めるとヘッダを出力するようなコードをバックエンド側で書かなければならないと、自動生成コードの都合上なってしまいます。レスポンスMIMEタイプはレスポンスボディの方で定義に入れてください。

path_specs["/examplePath"]["get"]["responses"]["200"]["headers"]["Content-Type"] = {
"schema": {
"type": "string",
"example": row['値例']
},
"description": row['項目説明']
}
elif row['項目(英名)'] == 'StatusCode':
path_specs["/examplePath"]["get"]["responses"]["200"]["headers"]["StatusCode"] = {
"schema": {
"type": "integer",
"example": int(row['値例'])
},
"description": row['項目説明']
}
else:
nested_property = {
row['項目(英名)']: {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[質問]
Sample.xlsx.csvを読み取らせたとき、下記のようなエラーが表示されました。キーがなくなる原因、または正しいファイルを頂けますか?内部で回して頂いて構いません。

KeyError: '項目(英名)'

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

こちらの環境でもcsvファイルによって発生することがあり疑問だったのですが、確認したところ、このJSONへの変換プログラムはOfficeスクリプトでcsvを整形せずに出力する場合で試した際のプログラムでした。今回のpushにはcsvを整形して出力するようなOfficeスクリプトと、そのスクリプトで生成したcsvファイルをサンプルとして格納しているため、実行がうまくいかなかったのだと思います。期待した結果通り実行できるcsvファイルをDiscordでお送りします。
ただ、csvを読み取る方式から変更しようとしているため実装として変わる可能性が高いです。

"type": "string" if row['データ型'] == 'string' else "integer",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[必須]objectやarrayにも対応してください。

"description": row['項目説明']
}
}
response_properties = nest_schema(hierarchy, response_properties, nested_property)

components_schemas["Response"] = {
"type": "object",
"properties": response_properties
}

# OpenAPIテンプレートに生成されたコンポーネントとパスを追加
oas_template["components"]["schemas"] = components_schemas
oas_template["paths"] = path_specs

# JSONファイルに出力
with open('openapi_spec.json', 'w', encoding='utf-8') as json_file:
json.dump(oas_template, json_file, ensure_ascii=False, indent=4)

print("OpenAPI specification has been generated successfully!")
Loading