Wednesday, 9 March 2016

How to get all items from a SharePoint Online list with all columns data?


Here is one of the ways to get all SPOL list items with all columns:


Method to fetch items:

private void btnGetListItems_Click(object sender, EventArgs e)
        {
            progressBar.Minimum = 0;
            progressBar.Maximum = 10;
            progressBar.Value = 1;
            var targetSite = new Uri(txtSiteUrl.Text.Trim());
            var login = txtUserID.Text.Trim();
            var password = txtPassword.Text;
            var securePassword = new SecureString();

            progressBar.Value = 3;
            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }

            var onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

            using (ClientContext clientContext = new ClientContext(targetSite))
            {
                try
                {
                    clientContext.Credentials = onlineCredentials;
                    Web web = clientContext.Web;
                    var list = clientContext.Web.Lists.GetByTitle(drpLists.SelectedItem.ToString());
                    var view = list.Views.GetByTitle("All Items");
                    clientContext.Load(view, v => v.ViewFields, v => v.ListViewXml);
                    clientContext.ExecuteQuery();
                    progressBar.Value = 4;
                    var query = new CamlQuery();
                    query.ViewXml = "<View><Query>" + view.ListViewXml + "</Query></View>";
                    var items = list.GetItems(query);
                    clientContext.Load(items);
                    clientContext.ExecuteQuery();
                    progressBar.Value = 5;
                    dtResults = new DataTable();
                    columnNames = new List<string>();
                    string clmn = string.Empty;
                    foreach (var listColumn in view.ViewFields)
                    {
                        if (listColumn.ToString().ToLower().Contains("linktitle"))
                        {
                            columnNames.Add("Title");
                            dtResults.Columns.Add("Title");
                            continue;
                        }
                        if (listColumn.ToString().ToLower().Contains("attachments"))
                            continue;
                        columnNames.Add(listColumn.ToString());

                        dtResults.Columns.Add(listColumn.ToString());
                    }
                    progressBar.Value = 6;
                 
                    FillGridView(items);
                    btnExportToExcel.Enabled = true;
                    progressBar.Value = 10;
                }
                catch (Exception ex)
                {
                    progressBar.Value = 10;
                    SWF.MessageBox.Show("Error: " + ex.Message);
                }
            }
        }

Method to fill items in DataTable/GridView:

        protected void FillGridView(ListItemCollection itemsColl)
        {
            try
            {
                progressBar.Value = 7;
                DataRow row;
                foreach (ListItem item in itemsColl)
                {
                    row = dtResults.NewRow();
                    foreach (string listColumn in columnNames)
                    {
                        try
                        {
                            row[listColumn] = item.FieldValues[listColumn].ToString();
                        }
                        catch (Exception ex)
                        {
                            row[listColumn] = string.Empty;
                        }

                    }
                    dtResults.Rows.Add(row);
                }
                progressBar.Value = 8;

                dataGridResults.DataSource = dtResults;
                try
                {
                    for (int col = 0; col < dtResults.Columns.Count; col++)
                    {
                        dtResults.Columns[col].ColumnName = dtResults.Columns[col].ColumnName.Replace("_x0020_", " ");
                        dtResults.Columns[col].ColumnName = dtResults.Columns[col].ColumnName.Replace("_x00", string.Empty);

                    }
                }
                catch (Exception ex) { }
            }
            catch (Exception ex)
            {
                progressBar.Value = 10;
                SWF.MessageBox.Show("Error while generating report: " + ex.Message);
            }

        }

Friday, 4 March 2016

How to export DataTable or Data Grid View data into Excel file ?


Method to convert DataTable rows into Excel file:

using SWF = System.Windows.Forms;using IO = System.IO;
 
public static string pPopulateExcel(DataTable myTable)
{  StringBuilder sb = new StringBuilder();
sb.AppendLine("<table cellspacing='0' cellpadding='4' rules='all' bordercolor='#CCCCCC' border='1' style='color:Black;background-color:White;border-color:#CCCCCC;border-width:1px;border-style:Solid;font-family:Tahoma;font-size:10pt;height:24px;border-collapse:collapse;'>");
sb.AppendLine("<tr style='color:Blue;background-color:aliceblue;font-weight:bold;'>");
sb.AppendLine("<td align='center'>Sl.No.</td>");
for (int llngCol = 0; llngCol < myTable.Columns.Count; llngCol++)
sb.AppendLine("<td align='center'>" + myTable.Columns[llngCol].ColumnName + "</td>");
sb.AppendLine("</tr>");
if (myTable.Rows.Count > 0)

{ 
int i = 1;
foreach (DataRow objDR in myTable.Rows)
{
 
sb.AppendLine("<tr class='body'>");

sb.AppendLine("<td align='right'>" + i + "</td>");
for (int llngCol = 0; llngCol < myTable.Columns.Count; llngCol++)
{
switch (myTable.Columns[llngCol].DataType.ToString())

{
 
case "System.Int32":
case "System.Decimal":
case "System.Double":
sb.AppendLine("<td align='right'>" + objDR[llngCol]);
break;
case "System.DateTime":
sb.AppendLine("<td align='center'>");
if (Convert.ToDateTime(objDR[llngCol]) != DateTime.MinValue)
sb.AppendLine((objDR[llngCol].ToString().Length == 0 ? "" : Convert.ToDateTime(objDR[llngCol].ToString()).ToString("dd-MMM-yyyy")) + "");
else
sb.AppendLine("&nbsp;");
break;
case "System.String":
sb.AppendLine("<td align='left'>" + objDR[llngCol]);
break;
default:
sb.AppendLine("<td align='center'>" + objDR[llngCol]);
break;

}
sb.AppendLine("</td>");

}
sb.AppendLine("</tr>");

i++;

}
sb.AppendLine("</table>");

}
else
sb.AppendLine("<tr class='body'><td colspan='" + (myTable.Columns.Count + 1) + "' align='left'>No Records found!</td></tr></table>");
return sb.ToString();

}

Export To Excel Button:

private void btnExportToExcel_Click(object sender, EventArgs e)
{ string XLSFileName = IO.Path.Combine(CurrentDirectory(), "Status Report " + DateTime.Now.ToString("ddMMMyyyyHHmm") + ".xls");

StringBuilder sbExcelText = new StringBuilder();

sbExcelText.AppendLine(ExcelUtil.pPopulateExcel((DataTable)dataGridResults.DataSource));

sbExcelText.AppendLine("<br />");

IO.File.WriteAllText(XLSFileName, sbExcelText.ToString());

SWF.MessageBox.Show("Completed! File: " + XLSFileName, "Status Report");

}


Method to get current directory path:

internal static string CurrentDirectory()

{
string lstrPath = System.IO.Path.GetDirectoryName(SWF.Application.ExecutablePath).ToLower();

if (lstrPath.Contains(@"\bin\debug") || lstrPath.Contains(@"\bin\release") || lstrPath.Contains(@"\bin\x86"))

{lstrPath = System.IO.Path.GetDirectoryName(SWF.Application.ExecutablePath).Substring(0, lstrPath.IndexOf(@"\bin"));

}return lstrPath + @"\Reports";
}