Friday 22 June 2012

Programmatically Add Data from CSV file into a SharePoint list as list item


In this post I will discuss various options to add data from a CSV file as SharePoint list Items in
SharePoint list.

Option 1 -  Using C# Code

Lets discuss the first option of doing this by C# codde. As you may know all the columns in a CSV file are seperated by ";". So the code reads each line of the csv file and then splits the columns in by “,” .  The code then creates a new Item in as existing SharePoint list and adds the values from the columns in list item fields.

StreamReader file;
string contents = string.Empty;
string filePath = "This can be reletive URL to CSV uploded in SharePoint";
SPFile spfile = web.GetFile(filePath);

if (spfile.Exists)
{
file = new StreamReader(spfile.OpenBinaryStream());
while ((line = file.ReadLine()) != null) -> Reading line by line of the csv file
{
char[] splitter = { ‘,’ };
String[] Array = line.ToString().Split(splitter);

// Now we got all the columns of the first line. Next add them to the  new list Item

using (SPSite oSiteCollection = new SPSite(SiteID))
{
using (SPWeb oWeb = oSiteCollection.OpenWeb(WebID))
{
SPList myList = oWeb.Lists["ListName"];
SPItem newEntry = myList.Items.Add();
newEntry["Col1"] = Array[0];
newEntry["Col2"] = Array[1];
newEntry["Col3"] = Array[2];
newEntry.Update();
myList.Update();
}}

Option 2 - Using Web Services

Take a look at this Article from Salaudeen Rajack

Option 3 - Using PowerShell Script

Take a look at this Excellent Script by Ravendra

# CSV path/File name
$contents = Import-Csv ‘C:\ShipDataMonthly.csv
# Web URL
$web = Get-SPWeb -webUrl ‘http://hweb22/Phase2′
# SPList name
$list = $web.Lists["ListName"]
# Delete
existing List Data, If not required remove this line
$list.get_items() | % { $_.Delete() }
# Iterate for each list column
foreach ($row in $contents)
{
$item = $list.items.add()
# Check if cell value is not null
if ($row.CsvCell1 -ne $null)
{$item["ListColumn1"] = $row.CsvCell1}
if ($row.CsvCell2 -ne $null)
{$item["ListColumn2"] = $row.CsvCell2}
if ($row.CsvCell3 -ne $null)
{$item["ListColumn3"] = $row.CsvCell3}
$item.update()
}



Ads by Google

1 comment:

  1. hi can u help me by your c# Solution? i have some errors. i create a timerjob and have some problems to insert your code in my Solution. one is e.g. that the variable "Line" is not defined

    ReplyDelete