关闭

Convert datatab to csv

标签: DataTable CSV
288人阅读 评论(0) 收藏 举报
分类:

///
/// 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;
            }
        }

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13296次
    • 积分:356
    • 等级:
    • 排名:千里之外
    • 原创:22篇
    • 转载:8篇
    • 译文:0篇
    • 评论:0条
    文章分类