Search code examples
c#excelrangeautofillworksheet

How to populate values from a list to a range of cells in an Excel using Excel.Interop?


I'm trying to populate values from a List in my model to a range of cells in an Excel file. The values in my student id List are = 11, 22, 33, 44 and i want them to be on Cell C8 to C11, respectively.

I tried to assign them as values for cell range ["C8:C11"] and AutoFill them.

private void IdFiller(IdGroupModel id, Worksheet sheet)

            foreach (var studentId in id.idList)
            {
                sheet.Range["B8"].Value = 1;
                sheet.Range["B8"].AutoFill(sheet.Range["B8:B19"], XlAutoFillType.xlFillSeries);

                sheet.Range["C8"].Value2 = studentId.name;
                //sheet.Range["C8"].AutoFill(sheet.Range["C8","C19"], XlAutoFillType.xlFillValues);

                sheet.Range["D8"].Value = studentId.age;
                sheet.Range["D8"].AutoFill(sheet.Range["D8:D19"], XlAutoFillType.xlFillValues);
            }
        }

But all i got in all of the cells is the value "44".


Solution

  • In your ForEach try add an Index counter.

    private void IdFiller(IdGroupModel id, Worksheet sheet)  { 
    int i =7;
     foreach (var studentId in id.idList)            
     {                
      i+=1;
      sheet.Range["B" + i.ToString()].Value = 1;                
      sheet.Range["C" + i.ToString()].Value2 = studentId.name;  
      sheet.Range["D" + i.ToString()].Value = studentId.age; 
     }        
    }