Skip to content

Instantly share code, notes, and snippets.

@stuncloud
Last active May 29, 2020 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuncloud/157e6a040fcde2a1a8e4195e53c4893e to your computer and use it in GitHub Desktop.
Save stuncloud/157e6a040fcde2a1a8e4195e53c4893e to your computer and use it in GitHub Desktop.
CSVファイルを良い感じに扱うためのモジュール
module CSV
dim table
hashtbl header
procedure Set(csv, hasHeader = TRUE)
if length(header) then
header = HASH_REMOVEALL
endif
table = split(csv, "<#CR>")
if hasHeader then
i = 0
for h in split(table[0], ",")
header[h] = i
i = i + 1
next
table = slice(table, 1)
else
i = 0
for h in split(table[0], ",")
header[i + 1] = i
i = i + 1
next
endif
for j = 0 to length(table) - 1
table[j] = split(table[j], ",")
next
fend
function OpenFile(path, hasHeader = TRUE)
if fopen(path, F_EXISTS) then
fid = fopen(path, F_READ)
csv = fget(fid, F_ALLTEXT)
fclose(fid)
Set(csv, hasHeader)
result = length(table) > 0
else
result = FALSE
endif
fend
function GetTable()
result = EMPTY
if length(table) then
result = table
endif
fend
function GetValue(row, column)
result = EMPTY
if length(table) > 0 and row <= length(table) and row > 0 then
if header[column, HASH_EXISTS] then
c = header[column]
result = table[row - 1][c]
endif
endif
fend
endmodule
call Module_CSV.uws
print "ヘッダ行付きCSVを読み込む"
if ! CSV.OpenFile("Test.csv") then
msgbox("ファイル読み込み失敗")
exit
endif
// テーブル全体を取得 (2次元配列)
for r in CSV.GetTable()
print join(r, "<#TAB>")
next
// 行番号と列名で値を抜き出す
print CSV.GetValue(1, "項目2")
print CSV.GetValue(2, "項目1")
print CSV.GetValue(3, "項目3")
// 存在しない行や列を指定するとemptyを返す
print CSV.GetValue(4, "項目3")
print CSV.GetValue(1, "項目4")
print "ヘッダ行のないCSVの場合はOpenFileの第二引数にFalseを渡す"
if ! CSV.OpenFile("Test.csv", FALSE) then
msgbox("ファイル読み込み失敗")
exit
endif
for r in CSV.GetTable()
print join(r, "<#TAB>")
next
// 行番号と列番号を指定
print CSV.GetValue(1, 1)
print CSV.GetValue(2, 2)
print CSV.GetValue(3, 3)
print CSV.GetValue(4, 1)
lp = getid(GET_LOGPRINT_WIN)
while status(lp, ST_VISIBLE)
sleep(0.1)
wend
項目1 項目2 項目3
001 AAAA 0123
002 BBBB 0456
003 CCCC 0789
@stuncloud
Copy link
Author

カンマを含む文字列には対応してません
abc,"d,e",fgh
みたいなのは
abc
"d
e"
fgh
になってしまいます

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment