[英]How to import excell file to DataGridView from a specific row in C#?
您可以使用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 來做到這一點:
檢查此鏈接以獲取代碼Read and Import Excel File into DataSet
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.