Program.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using MySql.Data.MySqlClient;
namespace CreateToCSV
{
class Program
{
static void Main(string[] args)
{
DataSet ds = new DataSet();
string connString = string.Format(@"Data Source = {0};Database={1};User ID={2};Password={3};allow user variables=true",
"xxxxxxxxx", "1_account", "root", "xxxxxxxxxx");
using(MySqlConnection conn = new MySqlConnection(connString))
{
string query = "SELECT " +
"*FROM " +
"VISIT_T";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = 120;
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
try
{
conn.Open();
da.Fill(ds);
conn.Close();
}
catch (System.Exception ex)
{
conn.Close();
}
}
StreamWriter sw = new StreamWriter("CSV.csv");
WriteToStream(sw, ds.Tables[0], false, false);
Console.ReadKey();
}
public static void WriteToStream(TextWriter stream, DataTable table, bool header, bool quoteall)
{
if (header)
{
for (int i = 0; i < table.Columns.Count; i++)
{
WriteItem(stream, table.Columns[i].Caption, quoteall);
if (i < table.Columns.Count - 1)
stream.Write(',');
else
stream.Write("\r\n");
}
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
WriteItem(stream, row[i], quoteall);
if (i < table.Columns.Count - 1)
stream.Write(',');
else
stream.Write("\r\n");
}
}
stream.Flush();
stream.Close();
}
private static void WriteItem(TextWriter stream, object item, bool quoteall)
{
if (item == null)
return;
string s = item.ToString();
if (quoteall || s.IndexOfAny("\",\x0A\x0D".ToCharArray()) > -1)
stream.Write("\"" + s.Replace("\"", "\"\"") + "\"");
else
stream.Write(s);
stream.Flush();
}
}
}
데이터베이스에 있는 데이터들입니다.
생성된 CSV.csv 파일입니다.
WriteToStream(TextWriter stream, DataTable table, bool header, bool quoteall)
세번째, 네번째 인자값으로 TRUE 주시면,
헤더값과 " " 표시됩니다.
출처 - http://knab.ws/blog/index.php?/archives/3-CSV-file-parser-and-writer-in-C-Part-1.html
'프로그래밍 > .NET' 카테고리의 다른 글
| [C#]LINQ to XML (0) | 2013.02.09 |
|---|---|
| [C#]const, readonly 상수 (1) | 2013.02.09 |
| [C#, MySQL]CSV파일의 데이터를 DB Export (0) | 2013.02.07 |
| [C#]ThreadPool (0) | 2013.02.05 |
| [C#]AutoResetEvent, ManualResetEvent (0) | 2013.02.05 |