First, connect to Excel, and read the spreadsheet into a DateTable
Pretty simple:
private static DataTable GenerateExcelData(string path)
{
OleDbConnection con;
if (Path.GetExtension(path) == ".xls")
{
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(path) == ".xlsx")
{
con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
else
{
throw new ApplicationException("Unknown date file type");
}
con.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", con); ;
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
con.Dispose();
return dt;
}
Getting that into a listview is harder (but a DataGridView is easy! Just set the DataSource to teh data table and it'll do it for you).
But, this will do something like what you want:
foreach (DataRow row in dt.Rows)
{
ListViewItem item = new ListViewItem(row[0].ToString());
for (int i = 1; i < dt.Columns.Count; i++)
{
item.SubItems.Add(row[i].ToString());
}
myListView.Items.Add(item);
}