从c#在excel表格中填充3列,而不需要跨行重复的值

本文关键字:不需要 excel 表格 3列 填充 | 更新日期: 2023-09-27 18:14:23

如果问题标题有点奇怪,请原谅。我想填充500 excel行与复合主键,其中包括3列。2列自动生成1到50之间的随机整数,第三列是2006年1月1日到2013年12月31日之间的日期。所以我想有500行,每一行都有3的不同组合。这是我的代码

        Type excelType = Type.GetTypeFromProgID("Excel.Application");
        dynamic excel = Activator.CreateInstance(excelType);
        excel.visible = true;
        excel.Workbooks.Add();
        Random rnd = new Random();
        dynamic sheet = excel.ActiveSheet;
        for (int i = 1; i <= 500; i++)
        {

            sheet.Cells[i, "A"] = rnd.Next(1,50);
            sheet.Cells[i, "B"] = rnd.Next(1,50);
            sheet.Cells[i, "C"] = RandomDay();

//这是检查是否存在组合以及是否分配新组合的地方

            for (int j = 0; j <= i + 1; j++)
            {
               if ( sheet.Cells[j + 1, "A"] == sheet.Cells[i, "A"] && 
                sheet.Cells[j + 1, "B"] == sheet.Cells[i, "B"] && 
                sheet.Cells[j + 1, "C"] == sheet.Cells[i, "C"])
                {
                    sheet.Cells[i, "A"] = rnd.Next(1,50);
                    sheet.Cells[i, "B"] = rnd.Next(1,50);
                    sheet.Cells[i, "C"] = RandomDay();
                }
            }
        }

    }

//随机日期方法

    public static DateTime RandomDay()
    {
        DateTime start = new DateTime(2006, 1, 1);
        DateTime end = new DateTime(2013, 12, 31);
        Random gen = new Random();
        int range = (end - start).Days;
        return start.AddDays(gen.Next(range));
    }

我真的不确定这是否会工作,加上它运行缓慢,它必须一遍又一遍地迭代来检查组合是否存在。有人有更好更快的解决方案吗?谢谢大家!

从c#在excel表格中填充3列,而不需要跨行重复的值

如果您的约束允许,我建议在excel之外生成唯一值,然后将它们插入excel,这样您就可以将它们放入元组字典中。

这样,您可以通过从您的值创建一个String并将其用作Dictionary中的键来检查预先存在的值。然后遍历Dictionary值并将它们插入到excel中。

哈希表(字典是什么)是恒定的查找时间,所以你将节省大量的时间来保证唯一性。

Dictionary<String,Tuple<int,int,DateTime>> store = new Dictionary<String, Tuple<int, int, DateTime>>();
for (int i = 0; i < 500; i++)
{
    int n1 = rnd.Next(1,50);
    int n2 = rnd.Next(1,50);
    DateTime dt = RandomDay();
   String key = n1.ToString() + n2.ToString() + dt.ToString();
    while (store.ContainsKey(key)) {
        n1 = rnd.Next(1,50);
        n2 = rnd.Next(1,50);
        dt = RandomDay();
        key = n1.ToString() + n2.ToString() + dt.ToString();
    }
    store.Add(key, new Tuple(n1, n2, dt));
}

要添加到excel中,只需遍历store.Values.