Importing excel data to datagrid using interop C# -
i have started on importing excel data datagrid.i found code , tried in on system i'm net getting in datagrid.can please tell me i'm doing wrong here. if has working code can u please share me. here code
using system; using system.collections.generic; using system.collections; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using microsoft.office.interop.excel; namespace windowsformsapplication1 { public partial class form1 : form { public form1() { initializecomponent(); } private void form1_load(object sender, eventargs e) { arraylist test = processworkbook("c:\\users\\s_kamalaksha_prabhu\\desktop\\book1.xlsx"); if (test != null) datagridview1.datasource = test; } public arraylist processworkbook(string filepath) { string file = filepath; microsoft.office.interop.excel.application excel = null; microsoft.office.interop.excel.workbook wkb = null; arraylist al = new arraylist(); try { excel = new microsoft.office.interop.excel.application(); wkb = exceltools.openbook(excel, file, false, true, false); microsoft.office.interop.excel.worksheet sheet = wkb.sheets["employees$"] microsoft.office.interop.excel.worksheet; microsoft.office.interop.excel.range range = null; if (sheet != null) range = sheet.get_range("a1:x6702", system.type.missing); if (range != null) { foreach (microsoft.office.interop.excel.range r in range) { al.add(r.text); } } } catch (exception ex) { //if need handle stuff console.writeline(ex.message); } { if (wkb != null) exceltools.releasercm(wkb); if (excel != null) exceltools.releasercm(excel); } return al; } //---------------- public static class exceltools { public static microsoft.office.interop.excel.workbook openbook(microsoft.office.interop.excel.application excelinstance, string filename, bool readonly, bool editable, bool updatelinks) { microsoft.office.interop.excel.workbook book = excelinstance.workbooks.open( filename, updatelinks, readonly, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, editable, type.missing, type.missing, type.missing, type.missing, type.missing); return book; } public static void releasercm(object o) { try { system.runtime.interopservices.marshal.releasecomobject(o); } catch { } { o = null; } } } } }
thanks.
i don't know supposed do:
foreach (microsoft.office.interop.excel.range r in range) { al.add(r.text); }
if want go through cells use range.cells. rows use range.rows guess if want fill grid you'll want like:
foreach (microsoft.office.interop.excel.range row in range.rows) { // add new row foreach (microsoft.office.interop.excel.range cell in row.cells) { // write cells' column on current row } }
Comments
Post a Comment