简体   繁体   中英

Export multiple listbox to excel or txt

I have 5 listboxes and I want to export the content of these 5 lisboxes to excel. I want that these listboxes would be shown in 5 columns. Listbox1[0] should be in the same row like listbox2[0] and so on ( listbox3[0], listbox4[0], listbox5[0] ).

I tried to copy all items from listboxes to datagridview and then export to excell but I can only choose one datasource, I didnt found a way to copy all 5 listboxes items to 5 columns in datagridview.

EDIT:

I solved with this code (thanks to my friend). Just created a datatable, imported lists items into it and exported datable to csv.

    //create datatable
    DataTable dt = new DataTable();
    //create datatable columns
    dt.Columns.Add("title++", typeof(string));
    dt.Columns.Add("title",typeof(string));
    dt.Columns.Add("season_name", typeof(string));
    dt.Columns.Add("episode_name", typeof(string));
    int rowCount = listBox1.Items.Count;

    //insert lists items into datatable columns
    for (int i = 0; i < rowCount; i++)
    {
        DataRow row = dt.NewRow();
        row["title++"] = listBox1.Items[i].ToString();
        row["title"] = listBox5.Items[i].ToString();
        row["season_name"] = listBox3.Items[i].ToString();
        row["episode_name"] = (listBox4.Items[i].ToString() + (" ") + listBox2.Items[i].ToString());

        dt.Rows.Add(row);
    }
    CreateCSVFile(dt, "output.csv");
    MessageBox.Show("Data exported.");

You can use the code below to write comma-separated values to a text file:

List<ListBox> listBoxes = new List<ListBox>();

foreach (Control c in Controls)
    if (c is ListBox)
        listBoxes.Add(c as ListBox);

int maxLineCount = listBoxes.Max(lb => lb.Items.Count);

StringBuilder sb = new StringBuilder();

for (int rowIndex = 0; rowIndex < maxLineCount; rowIndex++)
{                
    for (int columnIndex = 0; columnIndex < listBoxes.Count; columnIndex++)
    {
        if (listBoxes[columnIndex].Items.Count > rowIndex)
            sb.Append(listBoxes[columnIndex].Items[rowIndex]);

        sb.Append(", ");
    }

    sb.AppendLine();
}

File.WriteAllText("c:\\mytext.txt", sb.ToString());

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