System.Data.DataTable getdatafromexcelbycom (bool HasTitle, string fileName) {//openfiledialog openFile = new OpenFileDialog (); Openfile.filter = "Excel (*.xlsx) |*.xlsx| Excel (*.xls) |*.xls "; Openfile.initialdirectory = Environment.getfolderpath (Environment.SpecialFolder.Desktop); Openfile.multiselect = false; if (openfile.showdialog () = = DialogResult.Cancel) return null; var excelfilepath = Openfile.filename; Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application (); Sheets Sheets; Object omissiong = System.Reflection.Missing.Value; Workbook Workbook = null; System.Data.DataTable dt = new System.Data.DataTable (); try {if (app = = null) return null; Workbook = App. Workbooks.Open (FileName, Omissiong, Omissiong, Omissiong, Omissiong, Omissiong,Omissiong, Omissiong, Omissiong, Omissiong, Omissiong, Omissiong, Omissiong, Omissiong, Omissiong); Sheets = Workbook. worksheets; Read the data into the datatable Worksheet Worksheet = (Worksheet) sheets.get_item (1);//Read the first table if (Worksh * = = NULL) return null; int irowcount = worksheet. UsedRange.Rows.Count; int icolcount = worksheet. UsedRange.Columns.Count; Generate column header for (int i = 0; i < Icolcount; i++) {var name = "column" + i; if (hastitle) {var txt = (Range) worksheet. Cells[1, i + 1]). Text.tostring (); if (!string. IsNullOrEmpty (TXT)) name = txt; } while (dt. Columns.contains (name)) name = name + "_1";//duplicate row name will error. Dt. Columns.Add (New DataColumn (name, typeof (String))); }//Generate row data Range range; int rowidx = HasTitle? 2:1; for (int iRow = ROWIDX; IRow <= irowcount; irow++) {DataRow dr = dt. NewRow (); for (int icol = 1; icol <= icolcount; icol++) {range = (range) worksheet. Cells[irow, Icol]; DR[ICOL-1] = (range. Value2 = = null)? "": Range. Text.tostring (); } dt. Rows.Add (DR); } return DT; } catch {return null;} finally {workbook. Close (False, Omissiong, Omissiong); System.Runtime.InteropServices.Marshal.ReleaseComObject (workbook); workbook = null; App. Workbooks.close (); App. Quit (); System.Runtime.InteropServices.Marshal.ReleaseComObject (APP); App = null; } }
C # Excel convert to DataTable