asp.net - Dynamically create data table based on incoming Excel data in C#? -
i'm trying import excel sheet data table in c#. keep getting out of bounds exception because columns value being hard coded me.
for (int c = 0; c <40; c++) { ... }
so rather hard coding , having bunch of empty columns listed on data table, there way count columns being passed in before create table? thereby allowing me create table dynamically around incoming data?
below code.
if (fileupload.hasfile) { datatable dt = new datatable(); (int c = 0; c <40; c++) { dt.columns.add(c.tostring(), typeof(string)); } using (stream filestream = fileupload.postedfile.inputstream) using (streamreader sr = new streamreader(filestream)) { string = null; while ((a = sr.readline()) != null) { dt.rows.add(a.split(new char[] { ',' }).toarray()); } } gridview1.datasource = dt; gridview1.databind();
try using instead:
datatable dt; using (stream filestream = fileupload.postedfile.inputstream) using (streamreader sr = new streamreader(filestream)) { string = null; while ((a = sr.readline()) != null) { string[] columns = a.split(','); if (dt == null) { dt = new datatable(); (int = 0; < columns.count(); i++) dt.columns.add(new datacolumn(i.tostring(), typeof(string))); } dt.rows.add(columns); } } gridview1.datasource = dt; gridview1.databind();
so long first row contains maximum number of columns rest of data has, should set.
if first row column names, modify code skip dt.rows.add(columns)
on first pass, , replace i.tostring()
columns[i].tostring()
name datacolumn
properly.
if columns/values surrounded quotation marks ("
) modify while
statement above this:
while ((a = sr.readline()) != null) { = a.substring(1, a.length - 2); string[] columns = a.split(new string[] { "\",\"" }, stringsplitoptions.none); if (dt == null) { dt = new datatable(); (int = 0; < columns.count(); i++) dt.columns.add(new datacolumn(i.tostring(), typeof(string))); } dt.rows.add(a.split(new char[] { ',' }).toarray()); }
that strip first , last "
overall string, split on ","
. might want play around though, , add code figure out how fields delimited, or have input fields can specify. is, if input variable in how defined.
Comments
Post a Comment