thắc mắc C# WPF - Bác nào có code copy dữ liệu từ excel dán vào datagrid view của WPF không


Senior Member
Bác nào có code copy dữ liệu từ excel dán vào datagrid view của WPF không. Cho em xin với. Làm theo google mà chưa được.
Cái em có cả binding nha mấy bác

Ting Tướng

Senior Member
private void btnImport_Click(object sender, EventArgs e)

txtDuongDan.Text = openFileDialog1.FileName;
string strCon = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source = '" + openFileDialog1.FileName + "';Extended Properties=\"Excel 12.0;HDR=YES;\"";
DataTable data = new DataTable();
using (OleDbConnection conn = new OleDbConnection(strCon))
OleDbCommand command = new OleDbCommand("select * from[Sheet1$]", conn);
OleDbDataAdapter objDA = new OleDbDataAdapter(command);
dataGridView1.DataSource = data;
C# 2.png

Nhớ bên toolbox thêm cái OpenFileDialog vào nhé!


Đã tốn tiền
private void PasteClipboardValue()
//Show Error if no cell is selected
if (dgvMark.SelectedCells.Count == 0)
MessageBox.Show("Please select a cell", "Paste", MessageBoxButtons.OK, MessageBoxIcon.Warning);

//Get the satring Cell
DataGridViewCell startCell = GetStartCell(dgvMark);
//Get the clipboard value in a dictionary
Dictionary<int, Dictionary<int, string>> cbValue = ClipBoardValues(Clipboard.GetText());

int iRowIndex = startCell.RowIndex;
foreach (int rowKey in cbValue.Keys)
int iColIndex = startCell.ColumnIndex;
foreach (int cellKey in cbValue[rowKey].Keys)
//Check if the index is with in the limit
if (iColIndex <= dgvMark.Columns.Count - 1 && iRowIndex <= dgvMark.Rows.Count - 1)
DataGridViewCell cell = dgvMark[iColIndex, iRowIndex];

//Copy to selected cells if 'chkPasteToSelectedCells' is checked
if ((chkPasteToSelectedCells.Checked && cell.Selected) ||
cell.Value = cbValue[rowKey][cellKey];
private Dictionary<int, Dictionary<int, string>> ClipBoardValues(string clipboardValue)
Dictionary<int, Dictionary<int, string>> copyValues = new Dictionary<int, Dictionary<int, string>>();

String[] lines = clipboardValue.Split('\n');

for (int i = 0; i <= lines.Length - 1; i++)
copyValues = new Dictionary<int, string>();
String[] lineContent = lines.Split('\t');

//if an empty cell value copied, then set the dictionay with an empty string
//else Set value to dictionary
if (lineContent.Length == 0)
copyValues[0] = string.Empty;
for (int j = 0; j <= lineContent.Length - 1; j++)
copyValues[j] = lineContent[j];
return copyValues;

copy từ cửa sổ excel rồi paste vào datagridview nhé.