protected void Page_Load(object sender, EventArgs e) { FileInfo excel = new FileInfo(Server.MapPath(@"Xls/myData.xlsx")); using (var package = new ExcelPackage(excel)) { var workbook = package.Workbook; //*** Sheet 1 var worksheet = workbook.Worksheets.First(); //*** DataTable & DataSource DataTable dt = ConvertToDataTable(worksheet); this.myGridView.DataSource = dt; this.myGridView.DataBind(); } } private DataTable ConvertToDataTable(ExcelWorksheet oSheet) { int totalRows = oSheet.Dimension.End.Row; int totalCols = oSheet.Dimension.End.Column; DataTable dt = new DataTable(oSheet.Name); DataRow dr = null; for (int i = 1; i <= totalRows; i++) { if (i > 1) dr = dt.Rows.Add(); for (int j = 1; j <= totalCols; j++) { if (i == 1) dt.Columns.Add(oSheet.Cells[i, j].Value.ToString()); else dr[j - 1] = oSheet.Cells[i, j].Value.ToString(); } } return dt; }
ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท