-3

I have a problem because I can't export data from a listbox to Excel. I tried a lot of ways to do this but nothing happened. In Excel, I get only Excel.Kontrahenci (name of class) but I need export name of company to Excel.

IMG1

List<Kontrahenci> name = new List<Kontrahenci>();

private void UpdateBinding()
{
    listBox.ItemsSource = name;
    listBox.DisplayMemberPath = "Info";
    listBox1.DisplayMemberPath = "Info";
}

public void Open()
{
    Excel1.Application excel = new Excel1.Application();
    Excel1.Workbook workbook = excel.Workbooks.Open("D:\\Test.xlsx");
    Excel1.Worksheet sheet = (Excel1.Worksheet)workbook.Sheets["Arkusz1"];
    sheet.Select();

    Excel1.Worksheet x = excel.ActiveSheet as Excel1.Worksheet;

    Excel1.Range userRange = x.UsedRange;
    int countRecords = userRange.Rows.Count;
    int add = countRecords + 1;

    x.Cells[add, 1] = listBox.SelectedItem.ToString();

    workbook.Save();
    workbook.Close();
    excel.Quit();
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
M. Babik
  • 5
  • 3

1 Answers1

0

You need to override ToString method in your class like this:

class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public override string ToString() { return $"{FirstName} {LastName}"; }
}
JohnyL
  • 6,894
  • 3
  • 22
  • 41