简体   繁体   中英

Export listView table to Excel

Please help me how to solve the export problem. Problem in "Select". "ListViewItem.ListViewSubitemCollection" does not contain a definition for "Select" and could not find the extension method "Select" that takes the type "ListViewItem.ListViewSubitemCollection" as the first argument.

 private void excell_Click(object sender, EventArgs e)
{
    using(SaveFileDialog sfd=new SaveFileDialog() { Filter="Excel mon|*.xlsx", ValidateNames = true })
    {
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            SaveExel(sfd.FileName);
            MessageBox.Show("Ваши данные успешно сохранены.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

public void SaveExel(string filepath)
{
    Excel xl = new Excel(); //создаем инстанс

    foreach(ListViewItem item in listView1.Items)
    {
        var arr = item.SubItems.Select(x => x.Text).ToArray(); //*************

        xl.AddRow(arr);
    }

    xl.FileSave(filepath);
}

To use Linq you will need to cast SubItems as an IEnumerable like this:

IEnumerable<ListViewSubItem> subItems = item.SubItems.Cast<ListViewSubItem>();
var arr = subItems.Select(x => x.Text).ToArray();

You can however still do this without Linq by creating an array and then populating it using a for loop like this:

string[] arr = new string[item.SubItems.Count];

for(int i = 0; i < item.SubItems.Count; i++)
{
    arr[i] = item.SubItems[i].Text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM