【问题标题】:Export data from listbox to Excel [C#] [duplicate]将数据从列表框导出到 Excel [C#] [重复]
【发布时间】:2018-08-26 14:43:53
【问题描述】:

我遇到了一个问题,因为我无法将数据从列表框导出到 Excel。我尝试了很多方法来做到这一点,但没有任何反应。在 Excel 中,我只得到 Excel.Kontrahenci(班级名称),但我需要将公司名称导出到 Excel。

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();
}

【问题讨论】:

  • 既然有sheet 变量,为什么还需要x 变量?
  • 没问题,你只需要了解ToString是如何工作的,因此重复。

标签: c# excel wpf


【解决方案1】:

你需要像这样覆盖你的类中的ToString 方法:

class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public override string ToString() { return $"{FirstName} {LastName}"; }
}

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2014-02-06
    相关资源
    最近更新 更多