Tuesday 23 October 2007

Reading from an Excel Sheet and inserting into a Custom List in Sharepoint

//Add reference to using Microsoft.Office.Interop.Excel;

Application ExcelObj = new Application();
Workbook workBook = null;
Worksheet ws = null;

workBook = ExcelObj.Workbooks.Open(_tempFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

ws = new WorksheetClass();
ws = (Worksheet)workBook.ActiveSheet;

Range range = ws.get_Range("A" + i.ToString(), "J" + i.ToString());

System.Array myvalues = (System.Array)range.Cells.Value2;

if (myvalues.GetValue(1, 1) != null)//Check that the row has data
{
String example1 = (string)myvalues.GetValue(1, 1);
String example2 = (string)myvalues.GetValue(1, 2);

..
..
..

//Insert into Sharepoint

SPWeb web = SPContext.Current.Web;
SPListItemCollection listItems = web.Lists[_sharepointListName].Items;

SPListItem newListItem = listItems.Add();
newListItem[ColumnName1] = example1;
newListItem[ColumnName2] = example2;
..
..
..
..
}

//After working with Excel it is important to close the procsses that Excel uses other wise in your task manager you will find loads of Excel processes without being closed, the following method does a complete close down of all excel processes

private void ReleaseResources(Application ExcelObjk)
{
try
{
if (ws != null)
Marshal.ReleaseComObject(ws);

if (workBook != null)
{
workBook.Close(false, false, Type.Missing);
Marshal.ReleaseComObject(workBook);
}

if (ExcelObjk != null)
{
ExcelObjk.Workbooks.Close();
ExcelObjk.Quit();
Marshal.ReleaseComObject(ExcelObjk);
}
CallGarbageCollectorToCleanupReleasedMemory();
}
catch (Exception x)
{

}
}

private void CallGarbageCollectorToCleanupReleasedMemory()
{
GC.Collect();

//The bottom 2 lines are unnecessary and very dirty but can be used in worst case scenarious when you absolutely have to, have included here just to give an idea that this is possible

Process[] processes;
processes = System.Diagnostics.Process.GetProcessesByName("Excel");
foreach (Process p in processes)
p.Kill();
}

No comments: