tag:crieit.net,2005:https://crieit.net/tags/CSV%E8%AA%AD%E8%BE%BC/feed「CSV読込」の記事 - CrieitCrieitでタグ「CSV読込」に投稿された最近の記事2019-09-10T20:49:01+09:00
https://crieit.net/tags/CSV%E8%AA%AD%E8%BE%BC/feed
tag:crieit.net,2005:PublicArticle/153872019-09-10T20:49:01+09:002019-09-10T20:49:01+09:00https://crieit.net/posts/TSV-MarkdownTSVで定義した辞書をMarkdownで出力するツールを作った話
<h2 id="TL;DR"><a href="#TL%3BDR">TL;DR</a></h2>
<p>電子辞書が欲しくなったので作ることにしました。今回の要件は、品詞別の索引と全単語の索引、先頭の文字ごとの詳細解説があることです。</p>
<p>そこで辞書本体をmarkdownで書くことにしたのですが、ちまちま手で書くのは面倒くさい。なのでTSVを読み込んでmarkdownを吐くジェネレータを簡単に書いてみることにしました。</p>
<h2 id="TSVに格納する辞書の形式を考えてみた"><a href="#TSV%E3%81%AB%E6%A0%BC%E7%B4%8D%E3%81%99%E3%82%8B%E8%BE%9E%E6%9B%B8%E3%81%AE%E5%BD%A2%E5%BC%8F%E3%82%92%E8%80%83%E3%81%88%E3%81%A6%E3%81%BF%E3%81%9F">TSVに格納する辞書の形式を考えてみた</a></h2>
<p>TSVとは言いつつ、純粋なTSVは使っていません。まずは辞書のヘッダ部分です。</p>
<pre><code>BEGIN_HEADER
LANGUAGE_LONG Language Name
LANGUAGE_CODE LC(注1)
PHONETICAL_CHARS 頭文字になりうる文字の列挙(注2)
END_HEADER
</code></pre>
<ul>
<li>注1 これは2~3文字の言語コードです。<code>ja</code>, <code>en</code>など</li>
<li>注2 スペース区切りで列挙します。<code>a b c d e f g h i j k l m n o p q r s t u v w x y z</code>のように</li>
</ul>
<p>続いて、辞書の本体を考えてみました。</p>
<pre><code>BEGIN_DICTIONARY
単語 品詞ID(注1) 意味 関連語(注2)
END_DICTIONARY
</code></pre>
<ul>
<li>注1 品詞IDは任意の文字列です。</li>
<li>注2 関連語はスペース区切りで列挙します。<code>study learn</code>のように</li>
<li>単語は任意個この形式で列挙します。</li>
</ul>
<p>最後に、品詞の定義です。</p>
<pre><code>BEGIN_DEFINITION
品詞ID 品詞の名称
END_DEFINITION
</code></pre>
<p>このフィールドでは、DICTIONARYフィールド内で使用した品詞IDとその名称の対応(<code>NOUN</code>と名詞のような)を定義します。</p>
<h2 id="パーサーをざっくり書いてみる"><a href="#%E3%83%91%E3%83%BC%E3%82%B5%E3%83%BC%E3%82%92%E3%81%96%E3%81%A3%E3%81%8F%E3%82%8A%E6%9B%B8%E3%81%84%E3%81%A6%E3%81%BF%E3%82%8B">パーサーをざっくり書いてみる</a></h2>
<p>さて、このパーサーをざっくり書いてみました。</p>
<pre><code class="python">import csv
class ParseError(SyntaxError):
pass
def open_dict(dic_path: str) -> list:
with open(dic_path, encoding='utf-8') as f:
reader = csv.reader(f, delimiter='\t')
return list(reader)
def parse_dict(dic: list) -> dict:
ret = {}
state = 'none'
for i in dic:
if i[0] == 'BEGIN_HEADER':
if state != 'none':
raise ParseError('Unexpected BEGIN_HEADER tag.')
state = 'header'
ret['header'] = {}
continue
if i[0] == 'END_HEADER':
if state != 'header':
raise ParseError('Unexpected END_HEADER tag.')
state = 'none'
continue
if i[0] == 'BEGIN_DICTIONARY':
if state != 'none':
raise ParseError('Unexpected BEGIN_DICTIONARY tag.')
state = 'dictionary'
ret['dict'] = {}
continue
if i[0] == 'END_DICTIONARY':
if state != 'dictionary':
raise ParseError('Unexpected END_DICTIONARY tag.')
state = 'none'
continue
if i[0] == 'BEGIN_DEFINITION':
if state != 'none':
raise ParseError('Unexpected BEGIN_DEFINITION tag.')
state = 'definition'
ret['defs'] = {}
continue
if i[0] == 'END_DEFINITION':
if state != 'definition':
raise ParseError('Unexpected END_DEFINITION tag.')
state = 'none'
continue
if state == 'none':
continue
if state == 'header':
ret['header'][i[0]] = i[1]
continue
if state == 'dictionary':
if i[0] not in ret['dict']:
ret['dict'][i[0]] = {}
ret['dict'][i[0]][i[1]] = {
'meaning': i[2],
'reference': i[3].split(' ')
}
continue
if state == 'definition':
ret['defs'][i[0]] = i[1]
if state != 'none':
raise ParseError(f'A match pair tag of END_{state.upper()} not found.')
return ret
</code></pre>
<p>まぁ、本当に簡単に書いているので、解説することもほとんどないんですけれど……。ざっくり説明すると、tsvを読み込んで2次元配列に格納し、それを先ほど定義したフォーマットに従って辞書に格納しなおしているだけです。</p>
<p>次に、この生成した辞書から索引情報を抽出する関数を定義してみます。</p>
<pre><code class="python">def get_comparator(_order):
class _Comparator(str):
def __gt__(self, other):
order = list(_order)
for s, o in zip(self, other):
oi = order.index(o)
si = order.index(s)
if oi > si:
return True
if si > oi:
return False
return len(self) > len(other)
def __lt__(self, other):
order = list(_order)
for s, o in zip(self, other):
oi = order.index(o)
si = order.index(s)
if oi < si:
return True
if si < oi:
return False
return len(self) < len(other)
return _Comparator
def generate_indices(dic: dict):
chars = dic['header'].get(
'PHONETICAL_CHARS',
'a b c d e f g h i j k l m n o p q r s t u v w x y z').split(' ')
nodes = {i: {c: [] for c in chars} for i in dic['defs']}
nodes['ALPHABETICAL'] = {c: [] for c in chars}
comp = get_comparator(''.join(chars))
for word, data in dic['dict'].items():
nodes['ALPHABETICAL'][word[0]].append(word)
for kind in data:
nodes[kind][word[0]].append(word)
for i in nodes.values():
for j in i.values():
j.sort(key=comp)
return nodes
</code></pre>
<p><code>get_comparator</code>関数は、<code>PHONETICAL_CHARS</code>ヘッダフィールドで定義された辞書順に従って文字列を比較できるようにするラッパークラスを返す関数です。品詞ごとに単語の頭の文字の配列を作り、そこに単語のみを格納しているだけですね。<code>ALPHABETICAL</code>は全単語索引の情報で、定義されたすべての単語が登録されています。</p>
<p>次に意味情報と関連語情報を抽出する関数を定義します。</p>
<pre><code class="python">def generate_dict_content(dic: dict):
chars = dic['header'].get(
'PHONETICAL_CHARS',
'a b c d e f g h i j k l m n o p q r s t u v w x y z').split(' ')
defs = dic['defs']
contents = {i: [] for i in chars}
comp = get_comparator(''.join(chars))
for word, data in dic['dict'].items():
contents[word[0]].append({
'surface': word,
'meaning': [
(kind, meta['meaning'].split(' '))
for kind, meta in data.items()
],
'reference': [ref for d in data.values() for ref in d['reference']]
})
for c in contents.values():
c.sort(key=lambda x: comp(x['surface']))
return contents
</code></pre>
<p>この関数についての解説は、<code>generate_indices</code>関数とほぼ同じ動作のため割愛します。</p>
<p>これでTSVから単語情報を抽出する関数がそろいました。次はこれをmarkdownとして出力する関数を作っていきます。</p>
<h2 id="抽出した情報をMarkdownにしてみる"><a href="#%E6%8A%BD%E5%87%BA%E3%81%97%E3%81%9F%E6%83%85%E5%A0%B1%E3%82%92Markdown%E3%81%AB%E3%81%97%E3%81%A6%E3%81%BF%E3%82%8B">抽出した情報をMarkdownにしてみる</a></h2>
<p>索引を生成する関数を考えてみました。こんな感じです。</p>
<pre><code class="python">def generate_index_file(kind: str, defs: dict, index: list):
ret = f"# {defs[kind]}\n"
if kind == 'ALPHABETICAL':
ret += "\n## 品詞別インデックス\n"
for fp, kd in defs.items():
if fp != 'ALPHABETICAL':
ret += f"* [{kd}](./{fp.lower()}.md)\n"
for representative, content in index.items():
ret += f"\n## {representative.upper()}\n"
for word in content:
ret += f"* [{word}](./content/{word[0].upper()}.md#{word})\n"
return ret
</code></pre>
<p>すごいシンプルにかけて満足しています。あまりPythnoicではないと思いますが、そこは気にしないことにします。あと、<code>ALPHABETICAL</code>のページに品詞別インデックスへのリンクを表示することにしました。引数の意味ですが、<code>kind</code>は品詞ID、<code>defs</code>は品詞の定義、<code>index</code>には単語のリストを渡します。</p>
<p>続いて、単語の解説ページを生成する関数を考えてみました。</p>
<pre><code class="python">def generate_content_file(representative: str, words: list, defs: dict):
ret = f"# {representative.upper()}\n"
for word in words:
ret += f"\n## {word['surface']}\n"
ret += "意味: \n"
for i, (k, m) in enumerate(word['meaning']):
ret += f"{i + 1}. <{defs[k]}> \n"
for ml in m:
ret += f" {ml} \n"
refs = [i for i in word['reference'] if i]
if refs:
ret += "\n関連語: \n"
for ref in refs:
ret += f"* [{ref}](./{ref[0].upper()}.md#{ref})\n"
return ret
</code></pre>
<p>引数の意味ですが、<code>representative</code>は代表の文字(ようするにそのページの単語に共通の頭文字)、<code>words</code>は単語とそのメタ情報、<code>defs</code>は品詞の定義をとります。</p>
<p>さて、最後にこれらの関数の動作を連結する関数を書きましょう。それで完成です。</p>
<pre><code class="python">def generate_markdown_files(dic: dict):
indices = generate_indices(dic)
content = generate_dict_content(dic)
chars = dic['header'].get(
'PHONETICAL_CHARS',
'a b c d e f g h i j k l m n o p q r s t u v w x y z').split(' ')
defs = dic['defs'].copy()
defs['ALPHABETICAL'] = "全単語索引"
return {
'content': {
i: generate_content_file(i, content[i], defs) for i in chars
},
'indices': {
('index'
if i == 'ALPHABETICAL'
else i.lower()): generate_index_file(i, defs, content)
for i, content in indices.items()
}
}
</code></pre>
<p>この関数はparseされたTSVをmarkdown形式の文字列に変換する関数です。ここまでに定義した関数を連結して整形された形にするのが役割ですね。</p>
<p>さて、これをファイルにdumpする関数を書いて、それで本当に完成です。</p>
<pre><code class="python">def dump_markdown(dic_path: str, dump_dir: dir):
dic_path = abspath(dic_path)
dump_dir = abspath(dump_dir)
files = generate_markdown_files(parse_dict(open_dict(dic_path)))
print('generating indices...')
for rep, con in files['indices'].items():
path = join(dump_dir, f'{rep}.md')
d = dirname(path)
if not exists(d):
md(d)
print(f'writing file: {path}')
with open(path, 'w', encoding='utf-8') as f:
f.write(con)
print('generating content...')
for rep, con in files['content'].items():
path = join(dump_dir, 'content', f'{rep.upper()}.md')
d = dirname(path)
if not exists(d):
md(d)
print(f'writing file: {path}')
with open(path, 'w', encoding='utf-8') as f:
f.write(con)
print('done.')
</code></pre>
<p>この関数は、コンソールコマンドとして実行されることを想定したものになっています。</p>
<p>最後に、ここまで書いたスクリプトの全体を示しておきます。</p>
<pre><code class="python">#-*- coding: utf-8;-*-
from os import makedirs as md
from os.path import join, exists, dirname, abspath
import csv
class ParseError(SyntaxError):
pass
def get_comparator(_order):
class _Comparator(str):
def __gt__(self, other):
order = list(_order)
for s, o in zip(self, other):
oi = order.index(o)
si = order.index(s)
if oi > si:
return True
if si > oi:
return False
return len(self) > len(other)
def __lt__(self, other):
order = list(_order)
for s, o in zip(self, other):
oi = order.index(o)
si = order.index(s)
if oi < si:
return True
if si < oi:
return False
return len(self) < len(other)
return _Comparator
def open_dict(dic_path: str) -> list:
with open(dic_path, encoding='utf-8') as f:
reader = csv.reader(f, delimiter='\t')
return list(reader)
def parse_dict(dic: list) -> dict:
ret = {}
state = 'none'
for i in dic:
if i[0] == 'BEGIN_HEADER':
if state != 'none':
raise ParseError('Unexpected BEGIN_HEADER tag.')
state = 'header'
ret['header'] = {}
continue
if i[0] == 'END_HEADER':
if state != 'header':
raise ParseError('Unexpected END_HEADER tag.')
state = 'none'
continue
if i[0] == 'BEGIN_DICTIONARY':
if state != 'none':
raise ParseError('Unexpected BEGIN_DICTIONARY tag.')
state = 'dictionary'
ret['dict'] = {}
continue
if i[0] == 'END_DICTIONARY':
if state != 'dictionary':
raise ParseError('Unexpected END_DICTIONARY tag.')
state = 'none'
continue
if i[0] == 'BEGIN_DEFINITION':
if state != 'none':
raise ParseError('Unexpected BEGIN_DEFINITION tag.')
state = 'definition'
ret['defs'] = {}
continue
if i[0] == 'END_DEFINITION':
if state != 'definition':
raise ParseError('Unexpected END_DEFINITION tag.')
state = 'none'
continue
if state == 'none':
continue
if state == 'header':
ret['header'][i[0]] = i[1]
continue
if state == 'dictionary':
if i[0] not in ret['dict']:
ret['dict'][i[0]] = {}
ret['dict'][i[0]][i[1]] = {
'meaning': i[2],
'reference': i[3].split(' ')
}
continue
if state == 'definition':
ret['defs'][i[0]] = i[1]
if state != 'none':
raise ParseError(f'A match pair tag of END_{state.upper()} not found.')
return ret
def generate_indices(dic: dict):
chars = dic['header'].get(
'PHONETICAL_CHARS',
'a b c d e f g h i j k l m n o p q r s t u v w x y z').split(' ')
nodes = {i: {c: [] for c in chars} for i in dic['defs']}
nodes['ALPHABETICAL'] = {c: [] for c in chars}
comp = get_comparator(''.join(chars))
for word, data in dic['dict'].items():
nodes['ALPHABETICAL'][word[0]].append(word)
for kind in data:
nodes[kind][word[0]].append(word)
for i in nodes.values():
for j in i.values():
j.sort(key=comp)
return nodes
def generate_dict_content(dic: dict):
chars = dic['header'].get(
'PHONETICAL_CHARS',
'a b c d e f g h i j k l m n o p q r s t u v w x y z').split(' ')
defs = dic['defs']
contents = {i: [] for i in chars}
comp = get_comparator(''.join(chars))
for word, data in dic['dict'].items():
contents[word[0]].append({
'surface': word,
'meaning': [
(kind, meta['meaning'].split(' '))
for kind, meta in data.items()
],
'reference': [ref for d in data.values() for ref in d['reference']]
})
for c in contents.values():
c.sort(key=lambda x: comp(x['surface']))
return contents
def generate_content_file(representative: str, words: list, defs: dict):
ret = f"# {representative.upper()}\n"
for word in words:
ret += f"\n## {word['surface']}\n"
ret += "意味: \n"
for i, (k, m) in enumerate(word['meaning']):
ret += f"{i + 1}. <{defs[k]}> \n"
for ml in m:
ret += f" {ml} \n"
refs = [i for i in word['reference'] if i]
if refs:
ret += "\n関連語: \n"
for ref in refs:
ret += f"* [{ref}](./{ref[0].upper()}.md#{ref})\n"
return ret
def generate_index_file(kind: str, defs: dict, index: list):
ret = f"# {defs[kind]}\n"
if kind == 'ALPHABETICAL':
ret += "\n## 品詞別インデックス\n"
for fp, kd in defs.items():
if fp != 'ALPHABETICAL':
ret += f"* [{kd}](./{fp.lower()}.md)\n"
for representative, content in index.items():
ret += f"\n## {representative.upper()}\n"
for word in content:
ret += f"* [{word}](./content/{word[0].upper()}.md#{word})\n"
return ret
def generate_markdown_files(dic: dict):
indices = generate_indices(dic)
content = generate_dict_content(dic)
chars = dic['header'].get(
'PHONETICAL_CHARS',
'a b c d e f g h i j k l m n o p q r s t u v w x y z').split(' ')
defs = dic['defs'].copy()
defs['ALPHABETICAL'] = "全単語索引"
return {
'content': {
i: generate_content_file(i, content[i], defs) for i in chars
},
'indices': {
('index'
if i == 'ALPHABETICAL'
else i.lower()): generate_index_file(i, defs, content)
for i, content in indices.items()
}
}
def dump_markdown(dic_path: str, dump_dir: dir):
dic_path = abspath(dic_path)
dump_dir = abspath(dump_dir)
files = generate_markdown_files(parse_dict(open_dict(dic_path)))
print('generating indices...')
for rep, con in files['indices'].items():
path = join(dump_dir, f'{rep}.md')
d = dirname(path)
if not exists(d):
md(d)
print(f'writing file: {path}')
with open(path, 'w', encoding='utf-8') as f:
f.write(con)
print('generating content...')
for rep, con in files['content'].items():
path = join(dump_dir, 'content', f'{rep.upper()}.md')
d = dirname(path)
if not exists(d):
md(d)
print(f'writing file: {path}')
with open(path, 'w', encoding='utf-8') as f:
f.write(con)
print('done.')
if __name__ == '__main__':
from sys import argv
dump_markdown(argv[1], argv[2])
</code></pre>
<p>はー。疲れました。はい、これでおそらくどの方面にも需要がないツールの完成です。「欲しかったから作った」の真骨頂ですね。最後までお付き合いいただき、ありがとうございました。</p>
frodo821tag:crieit.net,2005:PublicArticle/148852019-03-27T10:31:37+09:002019-03-27T10:37:44+09:00https://crieit.net/posts/WPF-TextFieldParser-CSV【WPF】TextFieldParser で CSVファイルを読み込む
<p>今回は「TextFieldParser」で CSVファイルを読み込んで、データを一括登録してみたいと思います。</p>
<p>プログラムは前回のものを流用。<br />
<a target="_blank" rel="nofollow noopener" href="https://www.doraxdora.com/blog/2017/06/20/post-1275/" target="_blank" rel="noopener" data-blogcard="1">Converter を使って DataGrid に表示する値を変更する</a></p>
<p>画面の変更<br />
画面にCSV読込ボタンを追加します。</p>
<p><img src="https://www.doraxdora.com/wp-content/uploads/2017/06/ESP000006.jpg" alt="image" /></p>
<pre><code class="xml"><Button x:Name="imp_button" Content="CSV読込" HorizontalAlignment="Left" Margin="250,273,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="imp_button_Click"/>
</pre>
MainWindow.xaml
<pre class="lang:xhtml decode:true"><Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="一覧" Height="350" Width="530">
<Window.Resources>
<ResourceDictionary Source="/Style/StyleDic.xaml"/>
</Window.Resources>
<Grid>
<Grid.Resources>
<local:KindConverter x:Key="KindConv"/>
</Grid.Resources>
<Label Content="名前:" Margin="10,10,0,0" Style="{StaticResource lb-normal}"/>
<TextBox x:Name="search_name" Margin="56,12,0,0" Style="{StaticResource tx-normal}"/>
<Label Content="種別:" Margin="201,10,0,0" Style="{StaticResource lb-normal}"/>
<ComboBox x:Name="search_kind" Margin="252,12,0,0" Style="{StaticResource cb-normal}"/>
<Button x:Name="search_button" Content="検索" Margin="432,12,0,0" Style="{StaticResource btn-normal}" Click="search_button_Click"/>
<DataGrid Name="dataGrid" HorizontalAlignment="Left" Margin="10,43,0,0" Width="497" Height="225" Style="{StaticResource grid-normal}" >
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding No}" ClipboardContentBinding="{x:Null}" Header="No" IsReadOnly="True" Width="50"/>
<DataGridTextColumn Binding="{Binding Name}" ClipboardContentBinding="{x:Null}" Header="名前" IsReadOnly="True" Width="100"/>
<DataGridTextColumn Binding="{Binding Sex}" ClipboardContentBinding="{x:Null}" Header="性別" IsReadOnly="True" Width="40"/>
<DataGridTextColumn Binding="{Binding Age}" ClipboardContentBinding="{x:Null}" Header="年齢" IsReadOnly="True" Width="40"/>
<DataGridTextColumn Binding="{Binding Kind, Converter={StaticResource KindConv<span>}</span><span>}</span>" ClipboardContentBinding="{x:Null}" Header="種別" IsReadOnly="True" Width="120"/>
<DataGridTextColumn Binding="{Binding Favorite}" ClipboardContentBinding="{x:Null}" Header="好物" IsReadOnly="True" Width="*"/>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="add_button" Content="追加" HorizontalAlignment="Left" Margin="10,273,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="add_button_Click"/>
<Button x:Name="upd_button" Content="更新" HorizontalAlignment="Left" Margin="90,273,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="upd_button_Click"/>
<Button x:Name="del_button" Content="削除" HorizontalAlignment="Left" Margin="170,273,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="del_button_Click"/>
<Button x:Name="imp_button" Content="CSV読込" HorizontalAlignment="Left" Margin="250,273,0,0" VerticalAlignment="Top" Width="75" Height="30" Click="imp_button_Click"/>
</Grid>
</Window>
</code></pre>
<p>参照ライブラリの追加<br />
<img src="https://www.doraxdora.com/wp-content/uploads/2017/06/ESP000001.jpg" alt="image" /><br />
<img src="https://www.doraxdora.com/wp-content/uploads/2017/06/ESP000002.jpg" alt="image" /></p>
<p>参照の追加から「Microsoft.VisualBasic.FileIO」を追加します。</p>
<p>MainWindow.xaml.cs に次の記述を追加します。</p>
<p>MainWindow.xaml.cs</p>
<pre><code>using System.IO;
using Microsoft.Win32;
using Microsoft.VisualBasic.FileIO;
</code></pre>
<p>CSV読込処理の追加<br />
更にCSV読み込みの処理を追加します。</p>
<p>MainWindow.xaml.cs</p>
<pre><code> /// <summary>
/// CSVファイル読み込み処理
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
private static List<Cat> readFile(string filePath)
{
FileInfo fileInfo = new FileInfo(filePath);
string ret = string.Empty;
List<Cat> list = new List<Cat>();
using (TextFieldParser tfp = new TextFieldParser(fileInfo.FullName, Encoding.GetEncoding("Shift_JIS")))
{
tfp.TextFieldType = FieldType.Delimited;
tfp.Delimiters = new string[] { "," };
tfp.HasFieldsEnclosedInQuotes = true;
tfp.TrimWhiteSpace = true;
while (!tfp.EndOfData)
{
string[] fields = tfp.ReadFields();
Cat cat = new Cat();
cat.No = int.Parse(fields[0]);
cat.Name = fields[1];
cat.Sex = fields[2];
cat.Age = int.Parse(fields[3]);
cat.Kind = fields[4];
cat.Favorite = fields[5];
list.Add(cat);
}
}
return list;
}
</code></pre>
<p>クリックイベント処理の追加<br />
CSV読込ボタンをクリックした際のイベントを追加します。</p>
<p>MainWindow.xaml.cs</p>
<pre><code> /// <summary>
/// CSV読込ボタンクリックイベント.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void imp_button_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.FileName = "";
ofd.DefaultExt = "*.csv";
if (ofd.ShowDialog() == false)
{
return;
}
List<Cat> list = readFile(ofd.FileName);
// 接続
int count = 0;
using (var conn = new SQLiteConnection("Data Source=SampleDb.sqlite"))
{
conn.Open();
// データを追加する
using (DataContext context = new DataContext(conn))
{
foreach (Cat cat in list) {
// 対象のテーブルオブジェクトを取得
var table = context.GetTable<Cat>();
// データが存在するかどうか判定
if (table.SingleOrDefault(x => x.No == cat.No) == null)
{
// データ追加
table.InsertOnSubmit(cat);
// DBの変更を確定
context.SubmitChanges();
count++;
}
}
}
conn.Close();
}
MessageBox.Show(count + " / " + list.Count + " 件 のデータを取り込みました。");
// データ再検索
searchData();
}
</code></pre>
<p>CSVの作成<br />
読み込むCSVファイルを作成します。</p>
<p>次の内容をファイルにコピペし、「データ.csv」などという名前で保存します。</p>
<pre><code> 1,そら,♂,6,01,犬の人形
2,りく,♂,5,02,人間
3,うみ,♀,4,03,高級ウェットフード
4,こうめ,♀,2,04,横取り
5,こなつ,♀,7,01,布団
</code></pre>
<p>CSVを読み込んでみる<br />
<img src="https://www.doraxdora.com/wp-content/uploads/2017/06/ESP000003-1.jpg" alt="image" /></p>
<p>データを削除した状態で、「CSV読込」ボタンをクリックします。</p>
<p>画像を撮り忘れましたが、<br />
ファイル選択ダイアログが表示されるので、作成したCSVファイルを選択します。</p>
<p><img src="https://www.doraxdora.com/wp-content/uploads/2017/06/ESP000005.jpg" alt="image" /></p>
<p><img src="https://www.doraxdora.com/wp-content/uploads/2017/06/ESP000006.jpg" alt="image" /></p>
<p>無事に未登録のデータが登録されました。</p>
<p>以外に簡単にできましたね。</p>
<p>ではでは。</p>
doraxdora