Search code examples
listentity-framework-4spreadsheetgear

copy a list to a SpreadSheetGear Irange


I have the following code:

        using (CPASEntities ctx = new CPASEntities())
        {
            IWorksheet ws = wb.Worksheets[0];
            ws.Name = "Summary";
            var tsm = (from x in ctx.tblTimesheetMasters
                       where x.TSID == TSID
                       select new
                       {
                           TimesheetID = x.TSID,
                           Comments = x.TSComments,
                           Vendor = x.tblVendor.Vendor_Name,
                           StartDate = x.TSStartDate,
                           Author = x.TSAuthor,
                           Approver = x.TSApprover,
                           Override_Approver = x.TSOverrideApprover,
                           Status = x.tblTimesheetStatu.TSStatusDesc
                       }
                      ).ToList();
            SpreadsheetGear.IRange range = ws.Cells["A1"];
            // I want to copy the entire tsm list to this range, including headings.

        }

As the comment states, I want to put that entire list into the ws worksheet starting at A1. I include the code in case it's easier to use a different construct. FWIW, there will be only one entry...TSID is the primary key. I can, of course, use the .FirstorDefault() construct if that is important. I thought it not important.


Solution

  • Your range is only one cell. You need a range big enough to contain all the cells the list would populate.

    To populate your worksheet with the list, you could do something like this.

        int iRow = 0;
        int iCol = 0;
        if (tsm.Count() > 0)
        {
          foreach (var prop in tsm[0].GetType().GetProperties())
          {
            ws.Cells[iRow, iCol].Value = prop.Name;
            iCol++;
          }
          iRow++;
          foreach (var t in tsm)
          {
            iCol = 0;
            foreach (var prop in t.GetType().GetProperties())
            {
              ws.Cells[iRow, iCol].Value = prop.GetValue(t, null);
              iCol++;
            }
            iRow++;
          }
        }
    

    If you want a range, you could add this line.

    SpreadsheetGear.IRange range = ws.Cells[0, 0, iRow - 1, iCol - 1];