Nguyễn phúc minh phầN 1 DataProvider



tải về 311.37 Kb.
trang3/3
Chuyển đổi dữ liệu07.03.2022
Kích311.37 Kb.
#51203
1   2   3
Buổi2 Nguyễn Phúc Minh DTH195307

KẾT NỐI 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 Microsoft.Office.Interop.Excel;

using System.Data.OleDb;

namespace KetNoiExcel

{

public partial class Form1 : Form



{

public Form1()

{

InitializeComponent();



}

private static string filePath = "F:\\test.xlsx";

//dọc

private void btnDoc_Click(object sender, EventArgs e)



{

OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filePath + "';Extended Properties=\"Excel 12.0;HDR=YES;\"");

{

conn.Open();



OleDbDataAdapter a = new OleDbDataAdapter("select * from[Sheet1$]", conn);

DataSet ds = new DataSet();

a.Fill(ds);

dg1.DataSource = ds.Tables[0];

conn.Close();

}
}
//ghi

private void docDL(string sheet)

{

using (OleDbConnection conn = new OleDbConnection(kn))



{

conn.Open();

OleDbDataAdapter objDA = new System.Data.OleDb.OleDbDataAdapter

("select * from[" +sheet + "$]", conn);

DataSet excelDataSet = new DataSet();

objDA.Fill(excelDataSet);

dg1.DataSource = excelDataSet.Tables[0];

}

}


private void btnGhi_Click(object sender, EventArgs e)

{

{//ghi du lieu vao file excel



using (OleDbConnection conn = new OleDbConnection(kn))

{

try



{

conn.Open();

OleDbCommand cmd = new OleDbCommand();

cmd.Connection = conn;

cmd.CommandText = @"Insert into[Sheet1$] (stt, hovaten, quequan) VALUES(‘1′,’Khoa’,’An Giang’);";

cmd.ExecuteNonQuery();

}

catch (Exception ex)



{

//exception here

}

finally


{

conn.Close();

conn.Dispose();

}

}



docDL("Sheet1");

}

}


//cap nhat

private void btnCapNhat_Click(object sender, EventArgs e)

{

{//UPDATE DU LIEU



using (OleDbConnection conn = new OleDbConnection(kn))

{

try



{

conn.Open();

OleDbCommand cmd = new OleDbCommand();

cmd.Connection = conn;

string cl = "UPDATE[Sheet1$] SET hovaten = '" +

txtHoVaTen.Text + "', quequan = '" +txtQueQuan.Text + "' where STT =" +txtSTT.Text;

cmd.CommandText = cl;

cmd.ExecuteNonQuery();

}

catch (Exception ex)



{

//exception here

}

finally


{

txtHoVaTen.Text = "";

txtQueQuan.Text = "";

conn.Close();

conn.Dispose();

}

docDL("Sheet1");



}

}

}


private void dg1_CellClick(object sender, DataGridViewCellEventArgs e)

{

if(e.RowIndex >= 0)



{

DataGridViewRow row = this.dg1.Rows[e.RowIndex];

txtSTT.Text = row.Cells[0].Value.ToString();

txtHoVaTen.Text = row.Cells[1].Value.ToString();

txtQueQuan.Text = row.Cells[2].Value.ToString();
txtSTT.Enabled = false;

}

}



}

}


tải về 311.37 Kb.

Chia sẻ với bạn bè của bạn:
1   2   3




Cơ sở dữ liệu được bảo vệ bởi bản quyền ©hocday.com 2024
được sử dụng cho việc quản lý

    Quê hương