C#从数据库导出数据到CSV
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.OracleClient; using System.Data; using System.IO; namespace TextCSV { class Program { static void Main(string[] args) { //用provide 报错,去掉就好了,注意需要引用oracleclient string strCon = "Password=egdb;User ID=egdb;Data Source=egdb;Persist Security Info=True"; OracleConnection con = new OracleConnection(strCon); con.Open(); OracleCommand cmd = new OracleCommand(); cmd.Connection = con; cmd.CommandText = "select * from menu_perm"; cmd.CommandType = CommandType.Text; OracleDataAdapter ad = new OracleDataAdapter(cmd); DataSet ds = new DataSet(); ad.Fill(ds); con.Close(); using (StreamWriter streamWriter = new StreamWriter(@"d:\1.csv", false, Encoding.Default)) { if (ds.Tables[0].Rows.Count > 0) { foreach (DataRow row in ds.Tables[0].Rows) { StringBuilder str = new StringBuilder(); foreach (DataColumn col in ds.Tables[0].Columns) { //插入“,”自动会分割成不同的行。 str.Append(row[col.Caption.ToString()].ToString()+","); } streamWriter.WriteLine(str.ToString()); } } streamWriter.Flush(); streamWriter.Close(); } } } }