CSVファイルをSystem.Data.DataTable
にロードして、CSVファイルに基づいてデータテートを作成するにはどうすればいいですか?
通常のADO.netの機能で可能ですか?
私はこれまで、OleDb
プロバイダーを使用してきました。しかし、数値の入った行を読み込む際に、テキストとして扱いたい場合に問題があります。しかし、schema.ini
ファイルを作成することで、この問題を回避することができます。ここでは私が使った方法を紹介します。
// using System.Data;
// using System.Data.OleDb;
// using System.Globalization;
// using System.IO;
static DataTable GetDataTableFromCsv(string path, bool isFirstRowHeader)
{
string header = isFirstRowHeader ? "Yes" : "No";
string pathOnly = Path.GetDirectoryName(path);
string fileName = Path.GetFileName(path);
string sql = @"SELECT * FROM [" + fileName + "]";
using(OleDbConnection connection = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly +
";Extended Properties=\"Text;HDR=" + header + "\""))
using(OleDbCommand command = new OleDbCommand(sql, connection))
using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
DataTable dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
return dataTable;
}
}
ADO.NetのODBCテキストドライバを使ったソリューションをご紹介します。
Dim csvFileFolder As String = "C:\YourFileFolder"
Dim csvFileName As String = "YourFile.csv"
'Note that the folder is specified in the connection string,
'not the file. That's specified in the SELECT query, later.
Dim connString As String = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" _
& csvFileFolder & ";Extended Properties=""Text;HDR=No;FMT=Delimited"""
Dim conn As New Odbc.OdbcConnection(connString)
'Open a data adapter, specifying the file name to load
Dim da As New Odbc.OdbcDataAdapter("SELECT * FROM [" & csvFileName & "]", conn)
'Then fill a data table, which can be bound to a grid
Dim dt As New DataTableda.Fill(dt)
grdCSVData.DataSource = dt
データを入力したら、ColumnNameなどのデータテートのプロパティを値付けして、ADO.Netのデータオブジェクトの力を余すところなく発揮することができます。
VS2008では、Linqを使って同じ効果を得ることができます。
注:これはthisSOの質問と重複しているかもしれません。