예제 #1
0
        public static DataTable ExcelToDataTable(string fileName)
        {
            DataTable dt = new DataTable();

            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                IApplication application = excelEngine.Excel;
                IWorkbook    workbook    = application.Workbooks.Open(fileName, ExcelParseOptions.Default, true, "", ExcelVersion.Xlsx); //可以访问打开的excel
                IWorksheet   sheet       = workbook.Worksheets[0];                                                                       //第一 个sheet
                for (int col = 1; col <= sheet.Columns.Length; col++)
                {
                    if (sheet.GetText(1, col) == null)
                    {
                        continue;
                    }
                    dt.Columns.Add(sheet.GetText(1, col), sheet.GetValueRowCol(1, col).GetType());
                }
                for (int i = 2; i <= sheet.Rows.Length; i++)
                {
                    DataRow dataRow = dt.NewRow();
                    for (int j = 1; j <= sheet.Columns.Length; j++)
                    {
                        dataRow[j - 1] = sheet.GetValueRowCol(i, j);
                    }
                    dt.Rows.Add(dataRow);
                }
            }
            return(dt);
        }