簡體   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