Jayanta Mukherjee

Jayanta Mukherjee

  • 2k
  • 105
  • 9.6k

How do I databind excel data to a listview in WPF using c# ?

Jan 23 2022 3:35 PM

In windows form applications, in the form load event I can load filtered excel file data to a listview by using the below code and also setting the properties of the listview GridLines to True & View to Details etc.

			ExcelPackage.LicenseContext =LicenseContext.NonCommercial;
			int lastRow = 0;
			using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(filename), false))
				ExcelWorksheet mainSheet = package.Workbook.Worksheets.First();

				for (int i = 2; i <= mainSheet.Dimension.End.Row; i++)
					if (!string.IsNullOrEmpty(mainSheet.Cells["A"+i].Text))
						lastRow =i;

				listView1.Columns.Add("Bill No.");
				listView1.Columns.Add("Bill Date");
				listView1.Columns.Add("Due Date");

				for (int row = 2; row <= lastRow; row++)
				{ // Row by row...
					ListViewItem itm = new ListViewItem();
					for (int col = 2; col < 6; col++)
					{ // ... Cell by cell...
						//filter the excel data by date range
						if (DateTime.Parse(mainSheet.Cells[row, 5].Text) >= DateTime.Today && DateTime.Parse(mainSheet.Cells[row, 5].Text) <= DateTime.Today.AddDays(10))
							itm.Text =mainSheet.Cells[row, 1].Text;
							itm.SubItems.Add(mainSheet.Cells[row, col].Text);

Now, when I create a listview in WPF using the code in XAML 

<ListView x:Name="listView1" Height="300" Width="500" />

I don't get the properties like Columns, AutoResizeColumns etc and get errors.

So how do I do this in WPF and also how do I databind the listview with filtered excel data so that when I change the source excel file (say by a button click event) the listview gets automatically updated ?


Answers (3)