【问题标题】:How to import excell file to DataGridView from a specific row in C#?如何将excel文件从C#中的特定行导入DataGridView?
【发布时间】:2019-12-25 08:40:16
【问题描述】:
我想将 Excel 值从第 2 行导入到 DataGridView,但不知道如何。如果可能的话,我想保留 datagridview 中的当前现有数据值不被删除,因此导入的数据只是在之后添加。
这是从 datagridview 导出的当前结果。我希望它成为要导入的模板,因此导入的数据只能从第二行读取。我根本不明白如何将 Excel 数据导入到 gridview,所以任何有用的链接都会非常有帮助。非常感谢
【问题讨论】:
标签:
c#
excel
datagridview
【解决方案1】:
您可以使用 Microsoft.Office.Interop.Excel 库
下面是一个例子:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace Office
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application excelApp = new Excel.Application();
excelApp.Visible = false;
var excelBook = excelApp.Workbooks.Open(@"C:\excelFile.xls");
var excelSheet = (Excel.Worksheet)excelBook.Sheets[1];
var lastrowR = excelSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
var lastrowC = excelSheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Column;
for (int i = 1; i <= lastrowC; i++)
{
dataGridView1.Columns.Add("Column"+i.ToString(), i.ToString());
}
for (int j = 1; j <= lastrowR; j++)
{
dataGridView1.Rows.Add();
}
for (int x=2; x <= 6; x++)
{
for (int y = 15; y <= 16; y++)
{
dataGridView1.Rows[y-14].Cells[x-1].Value = excelSheet.Cells[y, x].Value.ToString();
}
}
excelBook.Close();
excelApp.Quit();
}
}
}
打开 Excel 文件并获取所需的单元格并将它们放入 datagridview 中所需的单元格中
【解决方案2】:
使用 OleDbConnection 、 OleDbDataAdapter 、 DataSet 来做到这一点:
- 导入 System.Data。
- 使用 ADO.NET 读取内容(类似 SQL SELECT 命令)。
- 内容将在 DataSet 中
- dataGridView1.DataSource = datatSet.Tables[0];
查看此链接以获取代码Read and Import Excel File into DataSet