Tuesday, July 28, 2009

Data Import to a Sharepoint List

Example:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
namespace DataImport
{
class Program
{
static void Main(string[] args)
{
// Check there are enough command line parameters
if (args.Length <>[ []]");
return;
} char[] splitArray = { ',' };
int startRecord = 0;
int endRecord = int.MaxValue;
// Store the command line parameters.
string paramFileName = args[0];
string paramWeb = args[1];
string paramList = args[2];
// Get start record integer.
if (args.Length > 3)
{
if (args[3] != String.Empty)
{
startRecord = Convert.ToInt32(args[3]);
}
// Get end record integer.
if (args.Length > 4)
{
if (args[4] != String.Empty)
{ endRecord = Convert.ToInt32(args[4]);
}
}
}
// validate the start and end record
if (endRecord < startRecord)
{
Console.WriteLine("End record parameter must be greater than start record parameter");
return;
}
// open the CSV file for reading
using (StreamReader fileRdr = File.OpenText(paramFileName))
{
// connect to the site collection
using (SPSite spSite = new SPSite(paramWeb))
{
// open the root site
using (SPWeb spWeb = spSite.OpenWeb())
{
// get the list from the site
SPList spList = spWeb.Lists[paramList];
// read the fields in the header
string line = fileRdr.ReadLine();
string[] fieldNames = line.Split(splitArray);
// get an array of field from the list
// this assumes the field names match
// we need the field Id when inserting rows
SPField[] spFields = new SPField[fieldNames.Length];
for (int looper = 0; looper < fieldNames.Length; looper++)
{
string strName = fieldNames[looper];
SPField field = spList.Fields.GetField(strName);
spFields[looper] = field;
}
// get the next line
line = fileRdr.ReadLine();
// start counting from the 2nd line
int lineCount = 0;
// keep reading till we run out of file
while (!fileRdr.EndOfStream)
{ // if we are past or on the start record then
if (lineCount >= startRecord)
{ // a little bit of progress
if (lineCount % 10 == 0)
Console.Write(".");
// get the values from the line
string[] fieldValues = line.Split(splitArray);
// create a new list item
SPListItem newItem = spList.Items.Add();
// populate the values in the item using the
// SPFields we created earlier
for (int looper = 0; looper < fieldValues.Length; looper++)
{
newItem[spFields[looper].Id] = fieldValues[looper];
}
// update the item to the list
newItem.Update();
}
// see if we want to stop prematurely
if (lineCount >= endRecord) break;
lineCount++;
//read the next line
line = fileRdr.ReadLine();
if (fileRdr.EndOfStream)
{ string[] fieldValues = line.Split(splitArray);
// create a new list item
SPListItem newItem = spList.Items.Add();
// populate the values in the item using the
// SPFields we created earlier
for (int looper = 0; looper < fieldValues.Length; looper++)
{
newItem[spFields[looper].Id] = fieldValues[looper];
}
// update the item to the list
newItem.Update();
}
}
}
}
}
}
}
}

No comments: