1 DataSet ds = new DataSet(); 2 OpenFileDialog openFileDialog = new OpenFileDialog(); 3 openFileDialog.Filter = "Excel 2003 *.xls |*.xls"; 4 openFileDialog.ShowDialog(); 5 6 if (openFileDialog.FileNames.Length == 0) 7 { 8 MessageBox.Show("请选择文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); 9 return; 10 } 11 12 using (FileStream file = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read)) //using里面为打开该文件后自动释放 13 { 14 HSSFWorkbook hSSFWorkbook = new HSSFWorkbook(file); 15 dataGridView1.Rows.Clear(); 16 17 DataTable data = new DataTable(); 18 data.Rows.Clear(); 19 data.Columns.Add("姓名", typeof(String)); 20 21 data.Columns.Add("身份证号", typeof(String)); 22 23 try 24 { 25 26 for (int i = 0; i <= hSSFWorkbook.GetSheetAt(0).LastRowNum-1; i++) 27 { 28 29 30 if (!string.IsNullOrEmpty(hSSFWorkbook.GetSheetAt(0).GetRow(i + 1).GetCell(0).StringCellValue)) //判断是否为空格或空值,不导入为空值的excel行 31 { 32 data.Rows.Add(hSSFWorkbook.GetSheetAt(0).GetRow(i + 1).GetCell(0), hSSFWorkbook.GetSheetAt(0).GetRow(i + 1).GetCell(1)); //导入excel 33 } 34 35 36 } 37 } 38 catch (Exception ea) 39 { 40 MessageBox.Show("excel表格数据有误,请检查excel表格再试"+" "+ea); 41 return; 42 } 43 44 45 46 this.dataGridView1.DataSource = data; 47 48 dataGridView1.AllowUserToAddRows = false; 49 50 51 } 52 for (int i = 0; i < dataGridView1.Rows.Count; i++) //给行标题标数量 53 { 54 dataGridView1.Rows[i].HeaderCell.Value = (i + 1).ToString(); 55 56 } 57