如何使用ClosedXML将数组插入Excel中的单个行

时间:2017-07-10 11:56:16

标签: c# excel arraylist closedxml

我有一个数组,我需要将元素放在一行中,数组的每个元素都应该在不同的单元格中。

    SetContentView(Resource.Layout.Main);
    SupportActionBar.SetDisplayShowHomeEnabled(true);

    var chemicals = new List<Chemical>
    {
        new Chemical {Name = "Niacin", DrawableId = Resource.Drawable.Icon},
        new Chemical {Name = "Biotin", DrawableId = Resource.Drawable.Icon},
        new Chemical {Name = "Chromichlorid", DrawableId = Resource.Drawable.Icon},
        new Chemical {Name = "Natriumselenit", DrawableId = Resource.Drawable.Icon},
        new Chemical {Name = "Manganosulfate", DrawableId = Resource.Drawable.Icon},
        new Chemical {Name = "Natriummolybdate", DrawableId = Resource.Drawable.Icon},
        new Chemical {Name = "Ergocalciferol", DrawableId = Resource.Drawable.Icon},
        new Chemical {Name = "Cyanocobalamin", DrawableId = Resource.Drawable.Icon},
    };

    _recyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
    _adapter = new RecyclerViewAdapter(this,chemicals);
    _LayoutManager = new LinearLayoutManager(this);
    _recyclerView.SetLayoutManager(_LayoutManager);
    _recyclerView.SetAdapter(_adapter);//

我的数组有10个元素,excel文件生成一行,但在所有10列中,单元格值是数组的最后一个元素。我希望每个元素都在不同的列中。 A1 = arrayCompany [0],B1 = arrayCompany [1] ... 10thcolumn = arrayCompany [9]

3 个答案:

答案 0 :(得分:1)

            for (int index = 0; index < 10; index++)
            {
                var cell = range.Cell(1, index + 1);
                cell.Value = arrayCompany[index];
            }

这是有效的,但我想这个问题有一个更清晰的解决方案。

答案 1 :(得分:1)

有一个拉取请求可以在https://github.com/ClosedXML/ClosedXML/pull/398

缓解此问题

您可以使用

cell.InsertData(data: yourEnumerable, transpose: true);

答案 2 :(得分:0)

我用过这个:

worksheet.Cell(x, y).Value = toExport.AsEnumerable();

我的toExport变量是对象列表。它不仅枚举列的所有属性,还将每个实例插入新行。

这也适用于数组。