Export/Import CSV file from/to listitem Sharepoint

We are able to export items from Sharepoint list into CSV files (comma-separated-values) and do opposite too, import csv into Sharepoint list.

Export : using codes below, you will get csv as download-file. Prepare a list inside your site, named it “Item List”, with 3 columns : Title, Price, Description.

private void ExportToCsv()
{
	Response.Clear();
	Response.Buffer = true;
	Response.AddHeader("content-disposition", "attachment;filename=Itemrecord.csv");
	Response.Charset = "";
	Response.ContentType = "application/text";
		
	// get data
	DataTable dtItem = GetDataFromList();
	StringBuilder sb = new StringBuilder();
	if(dtItem != null)
	{
		// separate each column with comma
		foreach (DataColumn dc in dtItem.Columns)
		{
			sb.Append(dc.ColumnName + ',');
		}
		
		// newline for value
		sb.AppendLine();
		
		// get value
		foreach (DataRow dr in dtItem.Rows)
		{
			foreach (DataColumn dc in dtItem.Columns)
			{
				sb.Append(dr[dc.ColumnName].ToString() + ',');
			}
			sb.AppendLine();
		}
		
		Reponse.Output.Write(sb.ToString());
		Response.Flush();
		Response.End();
	}
}

private DataTable GetDataFromList()
{
	// I have a list 'Item List' with 3columns
	SPQuery query = new SPQuery();
	query.ViewFields = "<FieldRef Name='Title' />
						<FieldRef Name='Price' />
						<FieldRef Name='Description' />";
	SPList list = SPContext.Current.Site.RootWeb.Lists.TryGetList("Item List");
	SPListItemCollection itemColl = list.GetItems(query);
	
	return itemColl.GetDataTable();
}

As result, you will get file “Itemrecord.csv”, contains firstline as column name, nextline as values.

Continue reading