Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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);

}
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!")
7 changes: 7 additions & 0 deletions Python/pd_read_excel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import pandas as pd

excel_file = 'input.xlsx'
df_sheet_multi = pd.read_excel(excel_file, sheet_name=['入力項目定義','出力項目定義'], header=6)


print(df_sheet_multi)
Binary file added Sample/Sample.xlsx
Binary file not shown.
6 changes: 6 additions & 0 deletions Sample/Sample.xlsx.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
No,階層,項目名(日本語),項目名(英語),データ型,桁数,必須,入出力区分,種別,項目の説明,値の例
1,1,コンテンツタイプ,content-type,string,y,入力,HEADER,レスポンスヘッダーのコンテンツタイプ,application/json;charset=utf-8
Copy link
Member

Choose a reason for hiding this comment

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

[推奨]CSVのカラム数が一致しません。一部の実装系で正しく処理できず、表示ができないので、目視で対応するのが大変だなと思います。

Copy link
Author

Choose a reason for hiding this comment

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

Officeスクリプトを使ってcsv化した際に、Excel方眼紙に対して実行すると一部項目が抜けてしまう(うまく変換できない)ことは理解しており、その点pandasを使えばわざわざExcelをcsvに変換せずにpandas.DataFrameとしてうまく処理ができそうということもあり、Pythonだけでの実装を現在進めています。

2,1,HTTPステータスコード,http-status,number,3,y,入力,HEADER,HTTPのレスポンスコード,200
3,1,氏名,user-name,string,,y,入力,BODY,ユーザー氏名
4,1,生年月日,user-birth,string,,y,入力,BODY,ユーザー生年月日
5,1,電話番号,user-phone-number,string,,y,入力,BODY,ユーザー電話番号