Convert datatab to csv

///
/// This method is used to Convert DataTable to CSV ( comma seperated ) file.
///
///
///
///

public static void DataTable2CSV(DataTable table, string filename, string seperateChar)
{

StreamWriter sr = null;

try
{

sr = new StreamWriter(filename);
string seperator = "";
StringBuilder builder = new StringBuilder();
foreach (DataColumn col in table.Columns)
{

builder.Append(seperator).Append(col.ColumnName);

seperator = seperateChar;
}

sr.WriteLine(builder.ToString());

foreach (DataRow row in table.Rows)
{

seperator = "";
builder =
new StringBuilder();
foreach (DataColumn col in table.Columns)
{

builder.Append(seperator).Append(row[col.ColumnName]);
seperator = seperateChar;

}

sr.WriteLine(builder.ToString());

}

}

finally
{

if (sr != null)
{

sr.Close();

}

}

}

 

 

 

 

 private DataTable GetDataTableFromCSV(string path)
        {
            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=" + "Yes" + "\""))
            using (OleDbCommand command = new OleDbCommand(sql, connection))
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
            {
                DataTable dataTable = new DataTable() { Locale = CultureInfo.CurrentCulture };
                adapter.Fill(dataTable);
                return dataTable;
            }
        }

阅读更多
文章标签: DataTable CSV
个人分类: Code
博主设置当前文章不允许评论。

Convert CSV Files to XML with LINQ.zip

2009年01月20日 18KB 下载

没有更多推荐了,返回首页

不良信息举报

Convert datatab to csv

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭