微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将值从 Excel 单元格范围添加到 <List>

如何解决将值从 Excel 单元格范围添加到 <List>

数据来自 Excel,使用 ClosedXML。问题是我不知道列中有多少个值。也许5个,也许更多。因此,我希望 ClosedXML 考虑范围内所有填充的单元格并将它们添加到列表中。这是我的代码现在的样子:我从每个单元格中手动获取值。

var tasks = workbook.Worksheet(1);
Tasks = new List<Task>()
                        {
                            new Task()
                            {
                                TaskName = tasks.Cell("A2").GetFormattedString(),TaskStart = tasks.Cell("B2").GetFormattedString(),TaskEnd = tasks.Cell("C2").GetFormattedString(),TaskStatus = tasks.Cell("D2").GetFormattedString()
                            },new Task()
                            {
                                TaskName = tasks.Cell("A3").GetFormattedString(),TaskStart = tasks.Cell("B3").GetFormattedString(),TaskEnd = tasks.Cell("C3").GetFormattedString(),TaskStatus = tasks.Cell("D3").GetFormattedString()
                            }}

解决方法

您可以检查单元格中是否有内容,如果为真则添加任务。由于列是线性的,因此增加一个计数器并将其用作单元格名称的一部分。

var tasks = workbook.Worksheet(1);
var Tasks = new List<Task>();
int loopCount = 2; //your starting row

while(tasks.Cell("A" + loopCount).GetFormattedString().Length > 0)
{
    Tasks.Add(new Task()
    {
        TaskName = tasks.Cell("A" + loopCount).GetFormattedString(),TaskStart = tasks.Cell("B" + loopCount).GetFormattedString(),TaskEnd = tasks.Cell("C" + loopCount).GetFormattedString(),TaskStatus = tasks.Cell("D" + loopCount).GetFormattedString()
    }
    loopCount++;
}

我希望这很清楚并且可以帮助您朝着正确的方向前进。

,

我的建议是使用 LINQ 并遍历 ws.FirstCell().CurrentRegion.RowsUsed() 集合。

using (var wb = new XLWorkbook("test2.xlsx"))
{
    var ws = wb.Worksheets.First();

    var tasks = ws.FirstCell().CurrentRegion.RowsUsed()
        .Select(row => new Task()
        {
            TaskName = row.Cell(1).GetFormattedString(),TaskStart = row.Cell(2).GetFormattedString(),TaskEnd = row.Cell(3).GetFormattedString(),TaskStatus = row.Cell(4).GetFormattedString()
        })
        .ToList();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。