-1

I have a windows form application in c# where there are list of data in multiple listbox (around 56 in each listbox). here is an example:

  1. listbox1 contains data of name of students
  2. listbox2 contains data of address of students
  3. listbox3 contains percentage of students.

the list goes on with the student data. Now i need to print the data in excel in a button click event. the data should go in an ordered way .

I tried using the CSV helper but it only helped me for 1 set of list box i need to sent data from multiple list box.

var sw = new StreamWriter(@"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);

foreach (var Name in lbx.Items)
{
    csvWriter.WriteField(Name);
    csvWriter.NextRecord();
}
foreach (var Address in ptr.Items)
{
    csvWriter.WriteField(Address);
}
sw.Flush();

However, this doesn't solve the problem. Any help regarding the solution to this problem would be helpful. Any other method to solve the problem will be great.

4

1 回答 1

0

我很难确定您的配置的全部细节,但如果它像ListBox您为其写入值的两个控件一样简单,您可以轻松地执行以下操作:

var sw = new StreamWriter(@"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
int lbxCount = lbx.Items.Count;
int ptrCount = ptr.Items.Count;
for (int i = 0; i < Math.Max(lbx.Items.Count, ptr.Items.Count); i++)
{
    object lbxValue = lbxCount > i ? lbx.Items[i] : String.Empty;
    object ptrValue = ptrCount > i ? ptr.Items[i] : String.Empty;
    csvWriter.WriteField(lbxValue);
    csvWriter.WriteField(ptrValue);
    csvWriter.NextRecord();
}
sw.Flush();
sw.Close();

这决定了要写入的最大记录数 ( Math.Max(lbx.Items.Count, ptr.Items.Count) 基于最大ListBox.Items.Count

通过将循环更改为单个循环,您现在可以WriteField正确使用该方法。如果ListBox lbx不包含某个记录的值,则它使用 aString.Empty作为该记录的值。同样,ListBox ptr如果 中有更多项目,它对lbx.

如果您ListBox在单个表单上有许多控件并希望每个控件,您可以通过遍历所有ListBox控件并获取它们各自的Item.Count值来确定总体上的最大项目,如下所示:

var sw = new StreamWriter(@"output.csv");
var csvWriter = new CsvHelper.CsvWriter(sw);
int maxRecords = 0;
List<ListBox> listBoxes = new List<ListBox>();

// Add all ListBox controls to list
// Determine maximum number of items (in all ListBox controls)
foreach (Control control in Controls)
{
    if (control.GetType() == typeof(ListBox))
    {
        ListBox currentListBox = (ListBox)control;
        listBoxes.Add(currentListBox);
        if (currentListBox.Items.Count > maxRecords)
            maxRecords = currentListBox.Items.Count;
    }
}

// Write fields for each ListBox
for (int i = 0; i < maxRecords; i++)
{
    foreach (ListBox currentListBox in listBoxes)
    {
        if (currentListBox.Items.Count > i)
            csvWriter.WriteField(currentListBox.Items[i]);
        else
            csvWriter.WriteField(String.Empty);
    }
    csvWriter.NextRecord();
}
sw.Flush();
sw.Close();
于 2014-11-16T03:52:23.240 回答