How can I create a Excel document from a template with a stream?

Topics: Developer Forum, User Forum
Dec 5, 2008 at 3:11 PM
Hi,
I have managed to generate Excel sheets as streams (instead of a file), now I really need to use a template for some layout. I can't figure out how to do it though

Here is the modified ExcelPackage() which uses a stream instead of a file

        /// <summary>
        /// Creates a new instance of the ExcelPackage class based on a stream.
        /// </summary>
        /// <param name="stream">Creates a new ExcelPackage from a stream</param>
        public ExcelPackage(Stream stream)
        {
            _package = Package.Open(stream, FileMode.OpenOrCreate);
            // save a temporary part to create the default application/xml content type
            Uri uriDefaultContentType = new Uri("/default.xml", UriKind.Relative);
            PackagePart partTemp = _package.CreatePart(uriDefaultContentType, "application/xml");

            XmlDocument workbook = Workbook.WorkbookXml; // this will create the workbook xml in the package

            // create the relationship to the main part
            _package.CreateRelationship(Workbook.WorkbookUri, TargetMode.Internal, schemaRelationships + "/officeDocument");

            // remove the temporary part that created the default xml content type
            _package.DeletePart(uriDefaultContentType);
        }

How do I modify the following block for the same end result?

        /// <summary>
        /// Creates a new instance of the ExcelPackage class based on a existing template.
        /// WARNING: If newFile exists, it is deleted!
        /// </summary>
        /// <param name="newFile">The name of the Excel file to be created</param>
        /// <param name="template">The name of the Excel template to use as the basis of the new Excel file</param>
        public ExcelPackage(FileInfo newFile, FileInfo template)
        {
            _outputFolderPath = newFile.DirectoryName;
            if (template.Exists)
            {
                if (newFile.Exists)
                {
                    try
                    {
                        newFile.Delete();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("ExcelPackage Error: Target file already exists and is locked.", ex);
                    }
                }
                newFile = template.CopyTo(newFile.FullName);
                newFile.IsReadOnly = false;

                _package = Package.Open(newFile.FullName, FileMode.Open, FileAccess.ReadWrite);
            }
            else
                throw new Exception("ExcelPackage Error: Passed invalid TemplatePath to Excel Template");
        }