赞
踩
说明:文档介绍将 excel文件导入到 dataGridView 控件中的方法。
1.创建一个 dataGridView 控件 dataGridView_import_data,然后放置一个按键,给按键添加一个触发事件函数,函数内容如下。
2.在事件函数末尾添加了内存回收代码 ,测试时发现导入一个3M的excel文件后,软件占用内存会增加900M左右,添加GC.Collect();是为了快速让系统回收内存,如果不添加约几分钟后系统也会自动回收多余的内存。
GC.Collect();//强制进行垃圾回收
-
- //导入excel数据到表格
-
- private void button_wav_import_data_Click(object sender, EventArgs e)
- {
- OpenFileDialog openFileDialog = new OpenFileDialog();
- openFileDialog.Filter = "Excel Files|*.xlsx";
- openFileDialog.Title = "Select an Excel File";
-
- if (openFileDialog.ShowDialog() == DialogResult.OK)
- {
- string filePath = openFileDialog.FileName;
- try
- {
- using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
- {
- IWorkbook workbook = new XSSFWorkbook(fs);
- ISheet sheet = workbook.GetSheetAt(0); // 获取第一个工作表
-
- DataTable dt = new DataTable();
- IRow headerRow = sheet.GetRow(0);
-
- // 创建列
- for (int i = 0; i < headerRow.LastCellNum; i++)
- {
- dt.Columns.Add(Convert.ToString(headerRow.GetCell(i)));
- }
-
- // 添加行数据
- for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
- {
- IRow row = sheet.GetRow(i);
- DataRow dataRow = dt.NewRow();
-
- for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
- {
- if (row.GetCell(j) != null)
- {
- dataRow[j] = row.GetCell(j).ToString();
- }
- }
-
- dt.Rows.Add(dataRow);
- }
- dataGridView_import_data.DataSource = dt;
- }
-
- // 把列抬头名称赋值给 列的name
- string Columns_name = "";
- for (int i = 0; i < dataGridView_import_data.Columns.Count; i++)
- {
- Columns_name = dataGridView_import_data.Columns[i].HeaderText;
- dataGridView_import_data.Columns[i].Name = Columns_name;
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show("Error: " + ex.Message);
- }
- }
- GC.Collect();//强制进行垃圾回收
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。