在c#中填充一个列表框

我有一个列表框,我设法将Excel工作表绑定到列表框(在Internet上研究数小时之后)。

现在我需要从表单中读取值到列表框中,但无法find任何合适的解决scheme。

这是我迄今为止所做的:

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 

提前致谢..

问题是你的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 (row = 1; row < 10; row++){ string a = ""; for (col = 1; col < 6; col++){ a += ws.Cells[row, col].Value2+" "; } listBox1.Items.Add(a); } 

我们来分解这个问题

  1. 数据采集
  2. 收集的数据表示

数据收集(在Linq的帮助下):

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

data表示(如ListBox项目):

  listBox1.Items.AddRange(data);