Thursday, 10 March 2016

Download Excel file from the Document Library in the SharePoint 2010

SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPList doclib = web.Lists["Shared Documents"];
foreach (SPListItem itemin doclib.Items)
 {
    var fileName = item.File.Name;
    byte[] binFile = item.File.OpenBinary();
    SPFile fileToDownload = web.GetFile(doclib.RootFolder.Url +"/" + fileName);
    Int32 bufferLength = 4096;
    Int32 readLength = bufferLength;
    Byte[] buffer =new Byte[bufferLength];
    System.IO.Stream fstream = fileToDownload.OpenBinaryStream();
                Response.ContentType ="application/vnd.ms-excel";
                Response.AppendHeader("Content-Disposition","attachment; filename=" + fileName);
                while (readLength == buffer.Length)
                {
                    readLength = fstream.Read(buffer, 0, bufferLength);
                    Response.OutputStream.Write(buffer, 0, readLength);
                    if (readLength < bufferLength)break;
                }
               Response.End();
               Response.Flush();
   }

No comments:

Post a Comment