Exception when trying to export from a SharePoint List to Excel

31 views Asked by At

I'm writing an extension method for the List class, which will export a file from SharePoint List to Excel. To communicate with Excel I use CSOM and C# 4.0.

This is the code I already have:

public static bool ExportToExcel(this List list, ClientContext context, string outputPath)
{
    // Load list items
    CamlQuery query = CamlQuery.CreateAllItemsQuery();
    ListItemCollection items = list.GetItems(query);
    context.Load(items);
    context.ExecuteQuery();

    // Create new Excel package
    using (var excelPackage = new ExcelPackage())
    {
        var worksheet = excelPackage.Workbook.Worksheets.Add(list.Title);

        context.Load(list.Fields);
        context.ExecuteQuery();

        // Add column headers
        int columnIndex = 1;
        foreach (var field in list.Fields)
        {
            if (!field.Hidden)
            {
                worksheet.Cells[1, columnIndex].Value = field.Title;
                columnIndex++;
            }
        }

        // Add data rows
        int rowIndex = 2;
        foreach (var item in items)
        {
            columnIndex = 1;
            foreach (var field in list.Fields)
            {
                if (!field.Hidden)
                {
                    worksheet.Cells[rowIndex, columnIndex].Value =
                        item[field.InternalName]; // here the exception is raised
                    columnIndex++;
                }
            }
            rowIndex++;
        }

        // Save Excel package to file
        FileInfo excelFile = new FileInfo(outputPath + list.Title + ".xlsx");
        excelPackage.SaveAs(excelFile);
        return true;
    }
}

But when executing this the following exception is raised: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

0

There are 0 answers