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 System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
namespace read_excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
int rw = 0;
int cl = 1;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(@"C:\images\docs\salman.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
rw = range.Rows.Count;
List<student> li = new List<student>();
//
//data read code...............................................
for (int i = 2; i <= rw; i++)
{
student s = new student();
s.id=(int)(range.Cells[i,cl] as Excel.Range).Value;
s.Name = (string)(range.Cells[i, ++cl] as Excel.Range).Value;
s.Marks = (int)(range.Cells[i, ++cl] as Excel.Range).Value;
cl = 1;
li.Add(s);
}
//data read code...............................................
//
xlWorkBook.Close(true, null, null);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
dataGridView1.DataSource = li;
}
}
}
-----------------------------------------------------------------------------------------------------------
class student
{
public int id { get; set; }
public string Name { get; set; }
public int Marks { get; set; }
}