Advertisement
Guest User

Untitled

a guest
Sep 4th, 2017
468
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.60 KB | None | 0 0
  1. $host.Runspace.ThreadOptions = "ReuseThread"
  2.  
  3. function Get-ListData
  4. {
  5. param ($sCSOMPath, $sSiteUrl,$ListTitle,$sUserName,$sPassword,$FileName)
  6. try
  7. {
  8. Write-Host "Getting all Items from the list $($ListTitle)"
  9.  
  10. #Adding the Client OM Assemblies
  11. Add-Type -Path "C:\Microsoft.SharePoint.Client.dll"
  12. Add-Type -Path "C:\Microsoft.SharePoint.Client.Runtime.dll"
  13.  
  14. #SPO Client Object Model Context
  15. $spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($sSiteUrl)
  16. $spoCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($sUserName, $sPassword)
  17. #$spoCredentials = New-Object System.Net.NetworkCredential($sUserName, $sPassword)
  18. $spoCtx.Credentials = $spoCredentials
  19.  
  20. $web = $spoCtx.Web
  21. $List = $web.Lists.GetByTitle($ListTitle);
  22.  
  23. $caml="<View Scope='RecursiveAll'></View>"
  24. $cquery = New-Object Microsoft.SharePoint.Client.CamlQuery
  25. $cquery.ViewXml=$caml
  26. $listItems = $List.GetItems($cquery)
  27.  
  28. $spoCtx.Load($List)
  29. $spoCtx.Load($listItems)
  30. $spoCtx.ExecuteQuery()
  31.  
  32. $AllListItems = @()
  33.  
  34. foreach ($listitem in $listItems)
  35. {
  36. $Title =""
  37. $CreatedBy = "System Account"
  38. $ModifiedBy = "System Account"
  39.  
  40. #you can get custom fields of list also
  41. If([string]::IsNullOrEmpty($listitem.FieldValues["Title"]))
  42. {
  43. $Title = "No Title"
  44. }
  45. else
  46. {
  47. $Title =$listitem.FieldValues["Title"]
  48. }
  49.  
  50. $FieldCreatedBy = [Microsoft.SharePoint.Client.FieldUserValue]$listitem.FieldValues["Author"]
  51. $CreatedBy = $FieldCreatedBy.LookupValue
  52. $FieldModifiedBy = [Microsoft.SharePoint.Client.FieldUserValue]$listitem.FieldValues["Editor"]
  53. $ModifiedBy = $FieldModifiedBy.LookupValue
  54.  
  55. $AllListItems += New-Object -TypeName PSObject -Property @{
  56. ListTitle = $ListTitle
  57. ItemID=$listitem.ID
  58. ItemName=$Title
  59. CreatedBy = $CreatedBy
  60. ModifiedBy = $ModifiedBy
  61. CreatedDate = $listitem.FieldValues["Created"]
  62. ModifiedDate = $listitem.FieldValues["Modified"]
  63.  
  64. } | Select ListTitle,ItemID,ItemName,CreatedBy,ModifiedBy,CreatedDate,ModifiedDate
  65. }
  66. $AllListItems| Export-CSV ($sCSOMPath+""+$FileName+".csv") -NoTypeInformation -Append #-Encoding UTF8
  67.  
  68. $spoCtx.Dispose()
  69. Read-Host -Prompt "file created at $($sCSOMPath). Please presss any key to close this"
  70.  
  71.  
  72. }
  73. catch [System.Exception]
  74. {
  75. Write-Host -ForegroundColor Red $_.Exception.ToString()
  76. Read-Host -Prompt "Operation failed..! Press any key to close this and re run the script"
  77. }
  78. }
  79.  
  80.  
  81. $FileName = "All_ListItem_Collection"
  82. $sSiteUrl = "https://site collection url"
  83. $sUserName = "userid@domain.com"
  84. $sPassword = Read-Host -Prompt "Enter SharePoint online site password" -AsSecureString
  85. $ListTitle = "List Title"
  86.  
  87.  
  88.  
  89. $scriptpath = $MyInvocation.MyCommand.Path
  90. $dir = Split-Path $scriptpath
  91.  
  92.  
  93.  
  94. Get-ListData -sCSOMPath $dir -sSiteUrl $sSiteUrl -ListTitle $ListTitle -sUserName $sUserName -sPassword $sPassword -FileName $FileName
  95.  
  96. public static string siteUrl = "https://contoso.sharepoint.com";
  97. public static string username = "xyz@contoso.onmicrosoft.com";
  98. public static string password = "*******";
  99.  
  100. public static string spListName = "List1";
  101. public static string viewName = "All Items";
  102.  
  103. public static string excelName = "ListDataExcel1";
  104. public static string exportLocation = "C:\Export\";
  105.  
  106. public static void Main(string[] args)
  107. {
  108. try
  109. {
  110. DataTable table = new DataTable();
  111. Program p = new Program();
  112. table = p.GetDataTableFromListItemCollection();
  113.  
  114. #region Export to excel
  115. p.WriteDataTableToExcel(table, spListName, exportLocation + excelName + ".xlsx", "Details");
  116.  
  117. Console.WriteLine();
  118. Console.WriteLine();
  119. Console.ForegroundColor = ConsoleColor.Green;
  120. Console.WriteLine("List export to excel completed successfully.");
  121. Console.Read();
  122. #endregion
  123. }
  124. catch (Exception ex)
  125. {
  126. Console.WriteLine("Exception: " + ex.Message);
  127. Console.Read();
  128. }
  129. }
  130.  
  131. private DataTable GetDataTableFromListItemCollection()
  132. {
  133. string strWhere = string.Empty;
  134. string filePath = string.Empty;
  135.  
  136. DataTable dtGetReqForm = new DataTable();
  137. using (var clientContext = new ClientContext(siteUrl))
  138. {
  139. try
  140. {
  141. SecureString passWord = new SecureString();
  142. foreach (char c in password.ToCharArray()) passWord.AppendChar(c);
  143. clientContext.Credentials = new SharePointOnlineCredentials(username, passWord);
  144. Console.WriteLine("Connecting "" + siteUrl + """);
  145. Web Oweb = clientContext.Web;
  146. clientContext.Load(Oweb);
  147. clientContext.ExecuteQuery();
  148. List spList = clientContext.Web.Lists.GetByTitle(spListName);
  149. clientContext.Load(spList);
  150. clientContext.Load(spList.Views);
  151. clientContext.ExecuteQuery();
  152. Console.WriteLine("Getting List: " + spListName);
  153.  
  154. if (spList != null && spList.ItemCount > 0)
  155. {
  156. View view = spList.Views.GetByTitle(viewName);
  157. clientContext.Load(view);
  158. clientContext.ExecuteQuery();
  159. ViewFieldCollection viewFields = view.ViewFields;
  160. clientContext.Load(viewFields);
  161. clientContext.ExecuteQuery();
  162.  
  163. CamlQuery query = new CamlQuery();
  164. query.ViewXml = "<View><Query>" + view.ViewQuery + "</Query></View>";
  165. ListItemCollection listItems = spList.GetItems(query);
  166.  
  167. clientContext.Load(listItems);
  168. clientContext.ExecuteQuery();
  169.  
  170. if (listItems != null && listItems.Count > 0)
  171. {
  172. foreach (var field in viewFields)
  173. {
  174. dtGetReqForm.Columns.Add(field);
  175. }
  176.  
  177. foreach (var item in listItems)
  178. {
  179. DataRow dr = dtGetReqForm.NewRow();
  180.  
  181. #region download attachments
  182. if (Convert.ToBoolean(item["Attachments"].ToString()))
  183. {
  184. Folder folder = Oweb.GetFolderByServerRelativeUrl(Oweb.Url + "/Lists/" + spListName + "/Attachments/" + item["ID"]);
  185. clientContext.Load(folder);
  186. clientContext.ExecuteQuery();
  187.  
  188. FileCollection attachments = folder.Files;
  189. clientContext.Load(attachments);
  190. clientContext.ExecuteQuery();
  191. foreach (Microsoft.SharePoint.Client.File oFile in attachments)
  192. {
  193. ClientResult<Stream> data = oFile.OpenBinaryStream();
  194. clientContext.ExecuteQuery();
  195. filePath = exportLocation;
  196.  
  197. string subPath = item["ID"].ToString();
  198. bool exists1 = System.IO.Directory.Exists(filePath + "\" + subPath);
  199.  
  200. if (!exists1)
  201. System.IO.Directory.CreateDirectory(filePath + "\" + subPath);
  202.  
  203. Console.WriteLine("Downloading file: " + oFile.Name);
  204. var fileName = Path.Combine(filePath + "\" + subPath, oFile.Name);
  205. using (FileStream fileStream = System.IO.File.OpenWrite(fileName))
  206. {
  207. if (data != null)
  208. {
  209. using (var memory = new MemoryStream())
  210. {
  211. byte[] buffer = new byte[1024 * 64];
  212. int nread = 0;
  213.  
  214. while ((nread = data.Value.Read(buffer, 0, buffer.Length)) > 0)
  215. {
  216. memory.Write(buffer, 0, nread);
  217. }
  218. memory.Seek(0, SeekOrigin.Begin);
  219. memory.CopyTo(fileStream);
  220. }
  221. }
  222. }
  223. }
  224. }
  225. #endregion
  226. for (int i = 0; i < viewFields.Count; i++)
  227. {
  228. string key = viewFields[i];
  229. string value = string.Empty;
  230. //string type = item.FieldValues[i].GetType().ToString();
  231. if (item[key] != null)
  232. {
  233. if (i == viewFields.Count - 1)
  234. {
  235.  
  236. }
  237. if (item.FieldValues[key].GetType().Name == "FieldLookupValue" || item.FieldValues[key].GetType().Name == "FieldUserValue")
  238. {
  239. value = ((Microsoft.SharePoint.Client.FieldLookupValue)(item[key])).LookupValue;
  240. }
  241. else if (item.FieldValues[key].GetType().Name == "FieldUrlValue")
  242. {
  243. value = ((Microsoft.SharePoint.Client.FieldUrlValue)(item[key])).Description;
  244. }
  245. else
  246. {
  247. value = item[key].ToString();
  248. }
  249. }
  250.  
  251. dr[key] = value;
  252. }
  253.  
  254. dtGetReqForm.Rows.Add(dr);
  255. }
  256. }
  257. }
  258. }
  259. catch (Exception ex)
  260. {
  261. Console.WriteLine(ex.Message);
  262. }
  263. finally
  264. {
  265. if (clientContext != null)
  266. clientContext.Dispose();
  267. }
  268. }
  269. return dtGetReqForm;
  270.  
  271. }
  272.  
  273. public bool WriteDataTableToExcel(System.Data.DataTable dataTable, string worksheetName, string saveAsLocation, string ReporType)
  274. {
  275. Microsoft.Office.Interop.Excel.Application excel;
  276. Microsoft.Office.Interop.Excel.Workbook excelworkBook;
  277. Microsoft.Office.Interop.Excel.Worksheet excelSheet;
  278. Microsoft.Office.Interop.Excel.Range excelCellrange;
  279.  
  280. try
  281. {
  282. // Start Excel and get Application object.
  283. excel = new Microsoft.Office.Interop.Excel.Application();
  284.  
  285. // for making Excel visible
  286. excel.Visible = false;
  287. excel.DisplayAlerts = false;
  288.  
  289. // Creation a new Workbook
  290. excelworkBook = excel.Workbooks.Add(Type.Missing);
  291.  
  292. // Workk sheet
  293. excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelworkBook.ActiveSheet;
  294. excelSheet.Name = worksheetName;
  295.  
  296.  
  297. //excelSheet.Cells[1, 1] = ReporType;
  298. //excelSheet.Cells[1, 2] = "Date : " + DateTime.Now.ToShortDateString();
  299.  
  300. // loop through each row and add values to our sheet
  301. int rowcount = 1;
  302. int finalColumn = 1;
  303. foreach (DataRow datarow in dataTable.Rows)
  304. {
  305. int exclColumn = 1;
  306. rowcount += 1;
  307. for (int i = 1; i <= dataTable.Columns.Count; i++)
  308. {
  309. if (dataTable.Columns[i - 1].ColumnName != "Attachments" && !dataTable.Columns[i - 1].ColumnName.StartsWith("_") && dataTable.Columns[i - 1].ColumnName != "MetaInfo" && dataTable.Columns[i - 1].ColumnName != "owshiddenversion" && dataTable.Columns[i - 1].ColumnName != "FileRef" && dataTable.Columns[i - 1].ColumnName != "UniqueId" && dataTable.Columns[i - 1].ColumnName != "FSObjType" && dataTable.Columns[i - 1].ColumnName != "ContentTypeId" && dataTable.Columns[i - 1].ColumnName != "File_x0020_Type" && dataTable.Columns[i - 1].ColumnName != "SMLastModifiedDate" && dataTable.Columns[i - 1].ColumnName != "SMTotalSize" && dataTable.Columns[i - 1].ColumnName != "ItemChildCount" && dataTable.Columns[i - 1].ColumnName != "FolderChildCount" && dataTable.Columns[i - 1].ColumnName != "ScopeId" && dataTable.Columns[i - 1].ColumnName != "GUID" && dataTable.Columns[i - 1].ColumnName != "WorkflowInstanceID" && dataTable.Columns[i - 1].ColumnName != "FileDirRef" && dataTable.Columns[i - 1].ColumnName != "SortBehavior" && dataTable.Columns[i - 1].ColumnName != "FileLeafRef" && dataTable.Columns[i - 1].ColumnName != "SyncClientId" && dataTable.Columns[i - 1].ColumnName != "ProgId" && dataTable.Columns[i - 1].ColumnName != "AppEditor" && dataTable.Columns[i - 1].ColumnName != "WorkflowVersion" && dataTable.Columns[i - 1].ColumnName != "InstanceID" && dataTable.Columns[i - 1].ColumnName != "Order" && dataTable.Columns[i - 1].ColumnName != "Restricted" && dataTable.Columns[i - 1].ColumnName != "OriginatorId" && dataTable.Columns[i - 1].ColumnName != "AppAuthor")
  310. {
  311. // on the first iteration we add the column headers
  312. if (rowcount == 2)
  313. {
  314. excelSheet.Cells[1, exclColumn] = dataTable.Columns[i - 1].ColumnName;
  315. excelSheet.Cells.Font.Color = System.Drawing.Color.Black;
  316. }
  317.  
  318. if (datarow[i - 1].ToString() != "")
  319. excelSheet.Cells[rowcount, exclColumn] = datarow[i - 1].ToString();
  320. else
  321. excelSheet.Cells[rowcount, exclColumn] = null;
  322.  
  323. //for alternate rows
  324. if (rowcount > 2)
  325. {
  326. if (i == dataTable.Columns.Count)
  327. {
  328. if (rowcount % 2 == 0)
  329. {
  330. excelCellrange = excelSheet.Range[excelSheet.Cells[rowcount, 1], excelSheet.Cells[rowcount, exclColumn]];
  331. FormattingExcelCells(excelCellrange, "#CCCCFF", System.Drawing.Color.Black, false);
  332. }
  333.  
  334. }
  335. }
  336.  
  337. exclColumn += 1;
  338. finalColumn = exclColumn - 1;
  339. }
  340. }
  341. }
  342.  
  343. // now we resize the columns
  344. excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[rowcount, finalColumn]];
  345. excelCellrange.EntireColumn.AutoFit();
  346. Microsoft.Office.Interop.Excel.Borders border = excelCellrange.Borders;
  347. border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
  348. border.Weight = 2d;
  349.  
  350.  
  351. excelCellrange = excelSheet.Range[excelSheet.Cells[1, 1], excelSheet.Cells[1, finalColumn]];
  352. FormattingExcelCells(excelCellrange, "#000099", System.Drawing.Color.White, true);
  353.  
  354.  
  355. //now save the workbook and exit Excel
  356. excelworkBook.SaveAs(saveAsLocation);
  357. excelworkBook.Close();
  358. excel.Quit();
  359. return true;
  360. }
  361. catch (Exception ex)
  362. {
  363. return false;
  364. }
  365. finally
  366. {
  367. excelSheet = null;
  368. excelCellrange = null;
  369. excelworkBook = null;
  370. }
  371.  
  372. }
  373.  
  374. public void FormattingExcelCells(Microsoft.Office.Interop.Excel.Range range, string HTMLcolorCode, System.Drawing.Color fontColor, bool IsFontbool)
  375. {
  376. range.Interior.Color = System.Drawing.ColorTranslator.FromHtml(HTMLcolorCode);
  377. range.Font.Color = System.Drawing.ColorTranslator.ToOle(fontColor);
  378. if (IsFontbool == true)
  379. {
  380. range.Font.Bold = IsFontbool;
  381. }
  382. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement