c# - Export SQL Server Data into CSV file -
i trying export data csv file sql server. have looked online , other support forums, can't find out how this? have written own code, doesn't work - keeps on loading... , fails.
please help. here code wrote.
sqlconnection sqlcon = new sqlconnection("removed"); string filename = "test.csv"; sqlcommand sqlcmd = new sqlcommand(); sqlcmd.commandtext = "select * products.products"; sqlcmd.connection = sqlcon; sqlcon.open(); using (var commandtext = new sqlcommand("select * products.products")) using (var reader = sqlcmd.executereader()) using (var outfile = file.createtext(filename)) { string[] columnnames = getcolumnnames(reader).toarray(); int numfields = columnnames.length; outfile.writeline(string.join(",", columnnames)); if (reader.hasrows) { while (reader.read()) { string[] columnvalues = enumerable.range(0, numfields) .select(i => reader.getvalue(i).tostring()) .select(field => string.concat("\"", field.replace("\"", "\"\""), "\"")) .toarray(); outfile.writeline(string.join(",", columnvalues)); } } } } private ienumerable<string> getcolumnnames(idatareader reader) { foreach (datarow row in reader.getschematable().rows) { yield return (string)row["columnname"]; } }
for it's worth, if want take query , dump contents somewhere, looks you're doing bit more work have to. complexity may add challenge in debugging.
a bare bones example of reading query , directing output file might this:
sqlconnection sqlcon = new sqlconnection("removed"); sqlcon.open(); sqlcommand sqlcmd = new sqlcommand( "select * products.products", sqlcon); sqldatareader reader = sqlcmd.executereader(); string filename = "test.csv"; streamwriter sw = new streamwriter(filename); object[] output = new object[reader.fieldcount]; (int = 0; < reader.fieldcount; i++) output[i] = reader.getname(i); sw.writeline(string.join(",", output)); while (reader.read()) { reader.getvalues(output); sw.writeline(string.join(",", output)); } sw.close(); reader.close(); sqlcon.close();
while may not dramatically shorter code listed, think it's simpler , easier debug, out of box. haven't tested this, can't works, although think it's pretty close.
another thing worth mentioning... neither of these true csv output. need sure handle embedded commas, return characters, etc, should in of output. that's easy enough do, though.
Comments
Post a Comment