当前位置:   article > 正文

C#: 导入excel文件到 dataGridView 控件

C#: 导入excel文件到 dataGridView 控件

说明:文档介绍将 excel文件导入到 dataGridView 控件中的方法。

1.创建一个 dataGridView 控件 dataGridView_import_data,然后放置一个按键,给按键添加一个触发事件函数,函数内容如下。

2.在事件函数末尾添加了内存回收代码 ,测试时发现导入一个3M的excel文件后,软件占用内存会增加900M左右,添加GC.Collect();是为了快速让系统回收内存,如果不添加约几分钟后系统也会自动回收多余的内存。

GC.Collect();//强制进行垃圾回收
  1. //导入excel数据到表格
  2. private void button_wav_import_data_Click(object sender, EventArgs e)
  3. {
  4. OpenFileDialog openFileDialog = new OpenFileDialog();
  5. openFileDialog.Filter = "Excel Files|*.xlsx";
  6. openFileDialog.Title = "Select an Excel File";
  7. if (openFileDialog.ShowDialog() == DialogResult.OK)
  8. {
  9. string filePath = openFileDialog.FileName;
  10. try
  11. {
  12. using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  13. {
  14. IWorkbook workbook = new XSSFWorkbook(fs);
  15. ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表
  16. DataTable dt = new DataTable();
  17. IRow headerRow = sheet.GetRow(0);
  18. // 创建列
  19. for (int i = 0; i < headerRow.LastCellNum; i++)
  20. {
  21. dt.Columns.Add(Convert.ToString(headerRow.GetCell(i)));
  22. }
  23. // 添加行数据
  24. for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
  25. {
  26. IRow row = sheet.GetRow(i);
  27. DataRow dataRow = dt.NewRow();
  28. for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
  29. {
  30. if (row.GetCell(j) != null)
  31. {
  32. dataRow[j] = row.GetCell(j).ToString();
  33. }
  34. }
  35. dt.Rows.Add(dataRow);
  36. }
  37. dataGridView_import_data.DataSource = dt;
  38. }
  39. // 把列抬头名称赋值给 列的name
  40. string Columns_name = "";
  41. for (int i = 0; i < dataGridView_import_data.Columns.Count; i++)
  42. {
  43. Columns_name = dataGridView_import_data.Columns[i].HeaderText;
  44. dataGridView_import_data.Columns[i].Name = Columns_name;
  45. }
  46. }
  47. catch (Exception ex)
  48. {
  49. MessageBox.Show("Error: " + ex.Message);
  50. }
  51. }
  52. GC.Collect();//强制进行垃圾回收
  53. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/58478
推荐阅读
相关标签
  

闽ICP备14008679号