c# - Data table to multiple CSV files -
i'm fetching records sql server 2012
table. i've used datatable
. want write fetched records multiple csv files
.
i've used stringbuilder
write column headers , fields csv file (single csv file).
but, new requirement first filter records based on columns , write multiple files.
- suppose i've 5 columns
col1
,col2
,col3
,col4
,col5
. - i need write
col1
,col2
,col5
once csv file ,col1
,col3
,col4
csv file. i want include column -
col0
first column added through code , not present in database. column derivedcol3
,col5
. this:dt.columns.add("col0", typeof(system.string)).setordinal(0);
row["col0"] = row["col3"] + "_" + row["col5"];
issue point 3 can't derive
col0
unless i'm fetching both rows -col3
,col5
datatable (dt). it's giving me error
system.argumentexception: column 'col3' not belong table selected.
please let me know how proceed?
code:
public static void createcsvfile(datatable dt, string csvpath, string csvfilename, int filesize) { stringbuilder firstline = new stringbuilder(); stringbuilder records = new stringbuilder(); int num = 0; int length = 0; dt.columns.add("update", typeof(system.string)).setordinal(0); dt.columns.add("key", typeof(system.string)).setordinal(1); ienumerable<string> columnnames = dt.columns.cast<datacolumn>().select(column => column.columnname); firstline.append(string.join(",", columnnames)); records.appendline(firstline.tostring()); length += records.tostring().length; int lastindex = dt.rows.count; foreach (var row1 in dt.rows.cast<datarow>().select((r, i) => new { row = r, index = })) { datarow row = row1.row; row["update"] = "update"; row["key"] = row["name"] + "_" + row["code"]; //putting field values in double quotes ienumerable<string> fields = row.itemarray.select(field => string.concat("\"", field.tostring().replace("\"", "\"\""), "\"")); records.appendline(string.join(",", fields)); length += records.tostring().length; if (length > filesize) { //create new file num++; file.writealltext(csvpath + csvfilename + datetime.now.tostring("yyyymmddhhmmss") + num.tostring("_000") + ".csv", records.tostring()); records.clear(); length = 0; records.appendline(firstline.tostring()); length += records.tostring().length; } else if (row1.index == lastindex - 1 && length != 0 && length < filesize) { //create new file num++; file.writealltext(csvpath + csvfilename + datetime.now.tostring("yyyymmddhhmmss") + num.tostring("_000") + ".csv", records.tostring()); records.clear(); length = 0; records.appendline(firstline.tostring()); length += records.tostring().length; } } }
Comments
Post a Comment