Search This Blog

Saturday, December 17, 2011

Programmatically Create and upload document in Sharepoint 2010 document library




http://download.microsoft.com/download/2/7/F/27FF6744-D970-4FFB-90B8-5226B2B8


Install this file.



\\Add Reference
\\C:\Program Files (x86)\Open XML SDK\V2.0\lib\DocumentFormat.OpenXml.dll

The type ‘System.IO.Packaging.Package’ is defined in an assembly that is not referenced. You must add a reference to   assembly ‘WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35′




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Threading;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;



public void CreateDocument(string docName)
        {
            using (MemoryStream memStream = new MemoryStream())
            {
                // Create a Wordprocessing document.
                using (WordprocessingDocument doc = WordprocessingDocument.Create(memStream, WordprocessingDocumentType.Document))
                {
                    // Add a new main document part.
                    doc.AddMainDocumentPart();
                    // Create the Document DOM.
                    doc.MainDocumentPart.Document = new Document(new Body(new Paragraph(new Run(new Text("Its a new Document!")))));
                    // Save changes to the main document part.
                    doc.MainDocumentPart.Document.Save();
                    //Adding Document to SharePoint
                    AddToSharePoint(memStream, docName);
                }
            }
        }
        protected void AddToSharePoint(MemoryStream memStream, string fileName)
        {
            using (SPSite spSite = new SPSite("http://igrid102:1974"))
            {
                //Get the document library object
                SPList docLib = spSite.RootWeb.Lists["Shared Documents"];
                SPFile file = docLib.RootFolder.Files.Add(fileName, memStream, true);
                file.Update();
            }
        }

No comments:

Post a Comment