繁体   English   中英

如何将excel文件从C#中的特定行导入DataGridView?

[英]How to import excell file to DataGridView from a specific row in C#?

我想将 Excel 值从第二行导入到 DataGridView 但不知道如何。 如果可能,我想保留 datagridview 中的当前现有数据值不会被删除,因此导入的数据只是在之后添加。

这是从 datagridview 导出的当前结果。 我希望它成为要导入的模板,因此导入的数据只能从第二行开始读取。 我完全不明白如何将 Excel 数据导入 gridview,因此任何有用的链接都会非常有帮助。 非常感谢

出口价值

您可以使用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 中的所需单元格中

使用 OleDbConnection 、 OleDbDataAdapter 、 DataSet 来做到这一点:

  • 导入系统.数据。
  • 使用 ADO.NET 读取内容(类似 SQL SELECT 命令)。
  • 内容将在数据集中
  • dataGridView1.DataSource = datatSet.Tables[0];

检查此链接以获取代码Read and Import Excel File into DataSet

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM