Jayanta Mukherjee

Jayanta Mukherjee

  • NA
  • 120
  • 42.8k

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("Party");
				listView1.Columns.Add("Bill No.");
				listView1.Columns.Add("Bill Date");
				listView1.Columns.Add("Amount");
				listView1.Columns.Add("Due Date");
				listView1.View=View.Details;

				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);
						}
						
					}
					
					if(itm.SubItems.Count>1)
					{
						listView1.Items.Add(itm);
					}
					
				}
				
				
			}
			
			listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
			listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

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 ?

Thanks!


Answers (3)