source đây ạ
//button Import
private void btnImport_Click(object sender, EventArgs e)
{
//Mở tệp tin
OpenFileDialog fopen = new OpenFileDialog();
//lọc ra đuôi excel
fopen.Filter = “(Tất cả các tệp)|.| (Các tệp excel)|*.xls”;
fopen.ShowDialog();
//xử lý
if (fopen.FileName != "")
{
lblPath.Text = fopen.FileName;
//tạo đối tượng Excel
Excel.Application app = new Excel.Application();
//mở file excel, mở wordbook để chứa
Excel.Workbook wb = app.Workbooks.Open(fopen.FileName);
//đọc dữ liệu
try
{
//mở sheet
//muốn tham chiếu đến sheet nào thì ta lấy workbook của sheet đó
Excel._Worksheet sheet = wb.Sheets[1]; // mảng sheet có chỉ số đầu là 1
//tham chiếu tới toàn bộ vùng dữ liệu
Excel.Range range = sheet.UsedRange;
//đọc dữ liệu
int rows = range.Rows.Count;//lấy số dòng
int cols = range.Rows.Count;//lấy số cột
//đọc dòng tiêu đề để tạo cột cho listview
for (int c = 1; c <= cols; c++)
{
string columnName = range.Cells[1, c].value.ToString();//Cells[dòng, cột]
ColumnHeader col = new ColumnHeader();
//gán thuộc tính
col.Text = columnName;
col.Width = 120;
lsvSinhVien.Columns.Add(col);
}
}
catch (Exception ex)
{
//thông báo lỗi
MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OKCancel);
}
}
else
{
MessageBox.Show("Bạn không chọn tệp tin nào", "Thông báo", MessageBoxButtons.OKCancel);
}
}