C# 在c中填充列表框#

C# 在c中填充列表框#,c#,excel,listbox,C#,Excel,Listbox,我有一个列表框,我设法将Excel工作表绑定到列表框(在互联网上搜索数小时后) 现在我需要将表中的值读入列表框,但无法找到任何合适的解决方案 这就是我到目前为止所做的:- private void LoadExcelSheet(string path, int sheet){ _Application excel = new Excel.Application(); Workbook wb; Worksheet ws; int row = 0; int col =

我有一个列表框,我设法将Excel工作表绑定到列表框(在互联网上搜索数小时后)

现在我需要将表中的值读入列表框,但无法找到任何合适的解决方案

这就是我到目前为止所做的:-

private void LoadExcelSheet(string path, int sheet){
   _Application excel = new Excel.Application();
   Workbook wb;
   Worksheet ws;

   int row = 0;
   int col = 0;

   wb = excel.Workbooks.Open(path);
   ws = wb.Worksheets[sheet];

   for (row = 1; row < 10; row++){
      for (col = 1; col < 6; col++){
         listBox1.Items.Add(ws.Cells[row, col].Value2);
      }
   }
 }
//------------------ end of LoadExcelSheet---------------------------

 this only display 1 row with each item of data on top of each other eg:-

aaaaaaaa
bbbbbbbb 
cccccccc
dddddddd

instead of: aaaaaaaa bbbbbbbb cccccccc dddddddd 
private void LoadExcelSheet(字符串路径,int sheet){
_应用程序excel=新建excel.Application();
工作手册wb;
工作表ws;
int行=0;
int col=0;
wb=excel.Workbooks.Open(路径);
ws=wb.工作表[工作表];
用于(行=1;行<10;行++){
用于(列=1;列<6;列++){
listBox1.Items.Add(ws.Cells[row,col].Value2);
}
}
}
//------------------装载单末尾---------------------------
这仅显示一行,每个数据项位于彼此的顶部,例如:-
AAAAA
bbbbbbbbbb
中交
dddddddd
代替:aaaaaa bbbbbbbb ccccccc dddddd

提前谢谢

如果要在包含列的循环中填充列表框,请尝试以下操作

for (row = 1; row < 10; row++){
    string a = "";
    for (col = 1; col < 6; col++){
        a += ws.Cells[row, col].Value2+" ";
     }
     listBox1.Items.Add(a);
}
for(行=1;行<10;行++){
字符串a=“”;
用于(列=1;列<6;列++){
a+=ws.Cells[行,列].Value2+“”;
}
列表框1.项目。添加(a);
}

问题在于for循环,请尝试以下方法:

for (var row = 1; row < 10; row++) 
{
     string r = "";
     for (var col = 1; col < 6; col++)
     {
         r += " " + ws.Cells[row, col].Value2;
     }
     listBox1.Items.Add(r.Trim());
}
for(变量行=1;行<10;行++)
{
字符串r=“”;
对于(变量col=1;col<6;col++)
{
r+=“”+ws.Cells[行,列].Value2;
}
listBox1.Items.Add(r.Trim());
}

让我们把问题分成两部分

  • 数据收集
  • 收集的数据表示法
  • 数据收集(在Linq的帮助下):

    数据
    表示(作为
    列表框
    项):


    嗯,嗯。列表框只有一个维度,但工作表有2个维度。Keith。。。谢谢你的支持。。。。然而,我尝试了大卫的解决方案。无论如何谢谢你!
     using System.Linq;
    
     ...  
    
     string[] data = Enumerable
       .Range(1, 9)                                   // 9 rows, starting from 1
       .Select(row => string.Join(" ", Enumerable     // cols are joined with space
          .Range(1, 5)                                // 5 columns in each row
          .Select(col => ws.Cells[row, col].Value2)))
       .ToArray();
    
     listBox1.Items.AddRange(data);