コード例 #1
0
        public void TestFail()  
        {
            Stream is1 = HSSFTestDataSamples.OpenSampleFileStream("Simple.xls");
            POIFSFileSystem fs = new POIFSFileSystem(is1);

            HSSFWorkbook wb = new HSSFWorkbook(fs);

            //set POIFS properties after constructing HSSFWorkbook
            //(a piece of code that used to work up to POI 3.0.2)
            SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.Create(fs.CreateDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
            summary1.Title=(title);
            //Write the modified property back to POIFS
            fs.Root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME).Delete();
            fs.CreateDocument(summary1.ToStream(), SummaryInformation.DEFAULT_STREAM_NAME);

            //save the workbook and read the property
            MemoryStream out1 = new MemoryStream();
            wb.Write(out1);
            out1.Close();

            POIFSFileSystem fs2 = new POIFSFileSystem(new MemoryStream(out1.ToArray()));
            SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.Create(fs2.CreateDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));

            //Assert.Failing assertion
            Assert.AreEqual(title, summary2.Title);
        }
コード例 #2
0
ファイル: TestEntryUtils.cs プロジェクト: 89sos98/npoi
        public void TestCopyRecursively()
        {
            POIFSFileSystem fsD = new POIFSFileSystem();
            POIFSFileSystem fs = new POIFSFileSystem();
            DirectoryEntry dirA = fs.CreateDirectory("DirA");
            DirectoryEntry dirB = fs.CreateDirectory("DirB");

            DocumentEntry entryR = fs.CreateDocument(new ByteArrayInputStream(dataSmallA), "EntryRoot");
            DocumentEntry entryA1 = dirA.CreateDocument("EntryA1", new ByteArrayInputStream(dataSmallA));
            DocumentEntry entryA2 = dirA.CreateDocument("EntryA2", new ByteArrayInputStream(dataSmallB));

            // Copy docs
            Assert.AreEqual(0, fsD.Root.EntryCount);
            EntryUtils.CopyNodeRecursively(entryR, fsD.Root);

            Assert.AreEqual(1, fsD.Root.EntryCount);
            Assert.IsNotNull(fsD.Root.GetEntry("EntryRoot"));

            EntryUtils.CopyNodeRecursively(entryA1, fsD.Root);
            Assert.AreEqual(2, fsD.Root.EntryCount);
            Assert.IsNotNull(fsD.Root.GetEntry("EntryRoot"));
            Assert.IsNotNull(fsD.Root.GetEntry("EntryA1"));

            EntryUtils.CopyNodeRecursively(entryA2, fsD.Root);
            Assert.AreEqual(3, fsD.Root.EntryCount);
            Assert.IsNotNull(fsD.Root.GetEntry("EntryRoot"));
            Assert.IsNotNull(fsD.Root.GetEntry("EntryA1"));
            Assert.IsNotNull(fsD.Root.GetEntry("EntryA2"));

            // Copy directories
            fsD = new POIFSFileSystem();
            Assert.AreEqual(0, fsD.Root.EntryCount);

            EntryUtils.CopyNodeRecursively(dirB, fsD.Root);
            Assert.AreEqual(1, fsD.Root.EntryCount);
            Assert.IsNotNull(fsD.Root.GetEntry("DirB"));
            Assert.AreEqual(0, ((DirectoryEntry)fsD.Root.GetEntry("DirB")).EntryCount);

            EntryUtils.CopyNodeRecursively(dirA, fsD.Root);
            Assert.AreEqual(2, fsD.Root.EntryCount);
            Assert.IsNotNull(fsD.Root.GetEntry("DirB"));
            Assert.AreEqual(0, ((DirectoryEntry)fsD.Root.GetEntry("DirB")).EntryCount);
            Assert.IsNotNull(fsD.Root.GetEntry("DirA"));
            Assert.AreEqual(2, ((DirectoryEntry)fsD.Root.GetEntry("DirA")).EntryCount);

            // Copy the whole lot
            fsD = new POIFSFileSystem();
            Assert.AreEqual(0, fsD.Root.EntryCount);

            EntryUtils.CopyNodes(fs, fsD, new List<String>());
            Assert.AreEqual(3, fsD.Root.EntryCount);
            Assert.IsNotNull(fsD.Root.GetEntry(dirA.Name));
            Assert.IsNotNull(fsD.Root.GetEntry(dirB.Name));
            Assert.IsNotNull(fsD.Root.GetEntry(entryR.Name));
            Assert.AreEqual(0, ((DirectoryEntry)fsD.Root.GetEntry("DirB")).EntryCount);
            Assert.AreEqual(2, ((DirectoryEntry)fsD.Root.GetEntry("DirA")).EntryCount);
        }
コード例 #3
0
        public void TestOK()
        {
            Stream is1 = HSSFTestDataSamples.OpenSampleFileStream("Simple.xls");
            POIFSFileSystem fs = new POIFSFileSystem(is1);

            //set POIFS properties before constructing HSSFWorkbook
            SummaryInformation summary1 = (SummaryInformation)PropertySetFactory.Create(fs.CreateDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
            summary1.Title = (title);

            fs.Root.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME).Delete();
            fs.CreateDocument(summary1.ToStream(), SummaryInformation.DEFAULT_STREAM_NAME);

            HSSFWorkbook wb = new HSSFWorkbook(fs);

            MemoryStream out1 = new MemoryStream();
            wb.Write(out1);
            out1.Close();

            //read the property
            POIFSFileSystem fs2 = new POIFSFileSystem(new MemoryStream(out1.ToArray()));
            SummaryInformation summary2 = (SummaryInformation)PropertySetFactory.Create(fs2.CreateDocumentInputStream(SummaryInformation.DEFAULT_STREAM_NAME));
            Assert.AreEqual(title, summary2.Title);

        }
コード例 #4
0
ファイル: HWPFDocument.cs プロジェクト: ctddjyds/npoi
        /**
         * Writes out the word file that is represented by an instance of this class.
         *
         * @param out The OutputStream to write to.
         * @throws IOException If there is an unexpected IOException from the passed
         *         in OutputStream.
         */
        public override void Write(Stream out1)
        {
            // Initialize our streams for writing.
            HWPFFileSystem docSys = new HWPFFileSystem();
            HWPFStream mainStream = docSys.GetStream("WordDocument");
            HWPFStream tableStream = docSys.GetStream("1Table");
            //HWPFOutputStream dataStream = docSys.GetStream("Data");
            int tableOffset = 0;

            // FileInformationBlock fib = (FileInformationBlock)_fib.Clone();
            // clear the offSets and sizes in our FileInformationBlock.
            _fib.ClearOffsetsSizes();

            // determine the FileInformationBLock size
            int fibSize = _fib.GetSize();
            fibSize += POIFSConstants.SMALLER_BIG_BLOCK_SIZE -
                (fibSize % POIFSConstants.SMALLER_BIG_BLOCK_SIZE);

            // preserve space for the FileInformationBlock because we will be writing
            // it after we write everything else.
            byte[] placeHolder = new byte[fibSize];
            mainStream.Write(placeHolder);
            int mainOffset = mainStream.Offset;

            // write out the StyleSheet.
            _fib.SetFcStshf(tableOffset);
            _ss.WriteTo(tableStream);
            _fib.SetLcbStshf(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;

            // get fcMin and fcMac because we will be writing the actual text with the
            // complex table.
            int fcMin = mainOffset;

            // write out the Complex table, includes text.
            _fib.SetFcClx(tableOffset);
            _cft.WriteTo(mainStream, tableStream);
            _fib.SetLcbClx(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;
            int fcMac = mainStream.Offset;

            // write out the CHPBinTable.
            _fib.SetFcPlcfbteChpx(tableOffset);
            _cbt.WriteTo(docSys, fcMin);
            _fib.SetLcbPlcfbteChpx(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;


            // write out the PAPBinTable.
            _fib.SetFcPlcfbtePapx(tableOffset);
            _pbt.WriteTo(mainStream, tableStream, _cft.GetTextPieceTable());
            _fib.SetLcbPlcfbtePapx(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;
            /*
              * plcfendRef (endnote reference position table) Written immediately
              * after the previously recorded table if the document contains endnotes
              * 
              * plcfendTxt (endnote text position table) Written immediately after
              * the plcfendRef if the document contains endnotes
              * 
              * Microsoft Office Word 97-2007 Binary File Format (.doc)
              * Specification; Page 24 of 210
              */
            _endnotesTables.WriteRef(_fib, tableStream);
            _endnotesTables.WriteTxt(_fib, tableStream);
            tableOffset = tableStream.Offset;


            /*
             * plcffndRef (footnote reference position table) Written immediately
             * after the stsh if the document contains footnotes
             * 
             * plcffndTxt (footnote text position table) Written immediately after
             * the plcffndRef if the document contains footnotes
             * 
             * Microsoft Office Word 97-2007 Binary File Format (.doc)
             * Specification; Page 24 of 210
             */
            _footnotesTables.WriteRef(_fib, tableStream);
            _footnotesTables.WriteTxt(_fib, tableStream);
            tableOffset = tableStream.Offset;


            // write out the SectionTable.
            _fib.SetFcPlcfsed(tableOffset);
            _st.WriteTo(docSys, fcMin);
            _fib.SetLcbPlcfsed(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;

            // write out the list tables
            if (_lt != null)
            {
                _fib.SetFcPlcfLst(tableOffset);
                _lt.WriteListDataTo(tableStream);
                _fib.SetLcbPlcfLst(tableStream.Offset - tableOffset);
            }

            /*
             * plflfo (more list formats) Written immediately after the end of the
             * plcflst and its accompanying data, if there are any lists defined in
             * the document. This consists first of a PL of LFO records, followed by
             * the allocated data (if any) hanging off the LFOs. The allocated data
             * consists of the array of LFOLVLFs for each LFO (and each LFOLVLF is
             * immediately followed by some LVLs).
             * 
             * Microsoft Office Word 97-2007 Binary File Format (.doc)
             * Specification; Page 26 of 210
             */

            if (_lt != null)
            {
                _fib.SetFcPlfLfo(tableStream.Offset);
                _lt.WriteListOverridesTo(tableStream);
                _fib.SetLcbPlfLfo(tableStream.Offset - tableOffset);
                tableOffset = tableStream.Offset;
            }

            /*
  * sttbfBkmk (table of bookmark name strings) Written immediately after
  * the previously recorded table, if the document contains bookmarks.
  * 
  * Microsoft Office Word 97-2007 Binary File Format (.doc)
  * Specification; Page 27 of 210
  */
            if (_bookmarksTables != null)
            {
                _bookmarksTables.WriteSttbfBkmk(_fib, tableStream);
                tableOffset = tableStream.Offset;
            }

            // write out the saved-by table.
            if (_sbt != null)
            {
                _fib.SetFcSttbSavedBy(tableOffset);
                _sbt.WriteTo(tableStream);
                _fib.SetLcbSttbSavedBy(tableStream.Offset - tableOffset);

                tableOffset = tableStream.Offset;
            }

            // write out the revision mark authors table.
            if (_rmat != null)
            {
                _fib.SetFcSttbfRMark(tableOffset);
                _rmat.WriteTo(tableStream);
                _fib.SetLcbSttbfRMark(tableStream.Offset - tableOffset);

                tableOffset = tableStream.Offset;
            }

            // write out the FontTable.
            _fib.SetFcSttbfffn(tableOffset);
            _ft.WriteTo(docSys);
            _fib.SetLcbSttbfffn(tableStream.Offset - tableOffset);
            tableOffset = tableStream.Offset;

            // write out the DocumentProperties.
            _fib.SetFcDop(tableOffset);
            byte[] buf = new byte[_dop.GetSize()];
            _fib.SetLcbDop(_dop.GetSize());
            _dop.Serialize(buf, 0);
            tableStream.Write(buf);



            // set some variables in the FileInformationBlock.
            _fib.SetFcMin(fcMin);
            _fib.SetFcMac(fcMac);
            _fib.SetCbMac(mainStream.Offset);

            // make sure that the table, doc and data streams use big blocks.
            byte[] mainBuf = mainStream.ToArray();
            if (mainBuf.Length < 4096)
            {
                byte[] tempBuf = new byte[4096];
                Array.Copy(mainBuf, 0, tempBuf, 0, mainBuf.Length);
                mainBuf = tempBuf;
            }

            // write out the FileInformationBlock.
            //_fib.Serialize(mainBuf, 0);
            _fib.WriteTo(mainBuf, tableStream);

            byte[] tableBuf = tableStream.ToArray();
            if (tableBuf.Length < 4096)
            {
                byte[] tempBuf = new byte[4096];
                Array.Copy(tableBuf, 0, tempBuf, 0, tableBuf.Length);
                tableBuf = tempBuf;
            }

            byte[] dataBuf = _dataStream;
            if (dataBuf == null)
            {
                dataBuf = new byte[4096];
            }
            if (dataBuf.Length < 4096)
            {
                byte[] tempBuf = new byte[4096];
                Array.Copy(dataBuf, 0, tempBuf, 0, dataBuf.Length);
                dataBuf = tempBuf;
            }


            // spit out the Word document.
            POIFSFileSystem pfs = new POIFSFileSystem();
            pfs.CreateDocument(new MemoryStream(mainBuf), "WordDocument");
            pfs.CreateDocument(new MemoryStream(tableBuf), "1Table");
            pfs.CreateDocument(new MemoryStream(dataBuf), "Data");
            WriteProperties(pfs);

            pfs.WriteFileSystem(out1);
        }
コード例 #5
0
        public void TestEmptyDocumentBug11744()
        {
            byte[] TestData = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            POIFSFileSystem fs = new POIFSFileSystem();
            fs.CreateDocument(new MemoryStream(new byte[0]), "Empty");
            fs.CreateDocument(new MemoryStream(TestData), "NotEmpty");
            MemoryStream output = new MemoryStream();
            fs.WriteFileSystem(output);

            // This line caused the error.
            fs = new POIFSFileSystem(new MemoryStream(output.ToArray()));

            DocumentEntry entry = (DocumentEntry)fs.Root.GetEntry("Empty");
            Assert.AreEqual(0, entry.Size, "Expected zero size");
            byte[] actualReadbackData;
            actualReadbackData = NPOI.Util.IOUtils.ToByteArray(new DocumentInputStream(entry));
            Assert.AreEqual(0, actualReadbackData.Length, "Expected zero read from stream");

            entry = (DocumentEntry)fs.Root.GetEntry("NotEmpty");
            actualReadbackData = NPOI.Util.IOUtils.ToByteArray(new DocumentInputStream(entry));
            Assert.AreEqual(TestData.Length, entry.Size, "Expected size was wrong");
            Assert.IsTrue(
                    Arrays.Equals(TestData,actualReadbackData), "Expected different data Read from stream");
        }
コード例 #6
0
ファイル: TestWrite.cs プロジェクト: xoposhiy/npoi
        public void TestDictionaryWithInvalidCodepage()
        {
            try
            {
                FileStream copy = File.Create( @"\Test-HPSF.ole2");
                //copy.deleteOnExit();

                /* Write: */
                FileStream out1 = copy;
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps1 = new MutablePropertySet();
                MutableSection s = (MutableSection)ps1.Sections[0];
                Hashtable m = new Hashtable(3, 1.0f);
                m[1] = "String 1";
                m[2] = "String 2";
                m[3] = "String 3";
                s.Dictionary = (m);
                s.SetFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1);
                int codepage = 12345;
                s.SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
                              codepage);
                poiFs.CreateDocument(ps1.GetStream(), "Test");
                poiFs.WriteFileSystem(out1);
                out1.Close();
                Assert.Fail("This Testcase did not detect the invalid codepage value.");
            }
            catch (IllegalPropertySetDataException)
            {
                //Assert.IsTrue(true);
            }
        }
コード例 #7
0
ファイル: TestWrite.cs プロジェクト: xoposhiy/npoi
        public void TestDictionary()
        {
            FileStream copy = File.Create( @"\Test-HPSF.ole2");
            //copy.deleteOnExit();

            /* Write: */
            FileStream out1 = copy;
            POIFSFileSystem poiFs = new POIFSFileSystem();
            MutablePropertySet ps1 = new MutablePropertySet();
            MutableSection s = (MutableSection)ps1.Sections[0];
            Hashtable m = new Hashtable(3, 1.0f);
            m[1] = "String 1";
            m[2] = "String 2";
            m[3] = "String 3";
            s.Dictionary = (m);
            s.SetFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1);
            int codepage = (int)Constants.CP_UNICODE;
            s.SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2,
                          codepage);
            poiFs.CreateDocument(ps1.GetStream(), "Test");
            poiFs.WriteFileSystem(out1);

            /* Read back: */
            POIFile[] psf = Util.ReadPropertySets(copy);
            Assert.AreEqual(1, psf.Length);
            byte[] bytes = psf[0].GetBytes();
            Stream in1 = new ByteArrayInputStream(bytes);
            PropertySet ps2 = PropertySetFactory.Create(in1);

            /* Check if the result is a DocumentSummaryInformation stream, as
             * specified. */
            Assert.IsTrue(ps2.IsDocumentSummaryInformation);

            /* Compare the property Set stream with the corresponding one
             * from the origin file and check whether they are equal. */
            Assert.IsTrue(ps1.Equals(ps2));

            out1.Close();
            copy.Close();
            File.Delete( @"\Test-HPSF.ole2");

        }
コード例 #8
0
ファイル: TestWrite.cs プロジェクト: xoposhiy/npoi
        /**
         * Performs the check described in {@link #TestReCreate()} for a single
         * POI filesystem.
         *
         * @param f the POI filesystem to check
         */
        private void TestRecreate(FileInfo f)
        {
            Console.WriteLine("Recreating file \"" + f.Name + "\"");
            
            /* Read the POI filesystem's property Set streams: */
            POIFile[] psf1 = Util.ReadPropertySets(_samples.GetFile(f.Name));

            /* Create a new POI filesystem containing the origin file's
             * property Set streams: */
            FileInfo fi = new FileInfo(f.Name);
            FileStream copy = File.Create(fi.Name);
            //copy.deleteOnExit();
            FileStream out1 = copy;
            POIFSFileSystem poiFs = new POIFSFileSystem();
            for (int i = 0; i < psf1.Length; i++)
            {
                Stream in1 =
                    new ByteArrayInputStream(psf1[i].GetBytes());
                PropertySet psIn = PropertySetFactory.Create(in1);
                MutablePropertySet psOut = new MutablePropertySet(psIn);
                MemoryStream psStream =
                    new MemoryStream();
                psOut.Write(psStream);
                psStream.Close();
                byte[] streamData = psStream.ToArray();
                poiFs.CreateDocument(new ByteArrayInputStream(streamData),
                                     psf1[i].GetName());
                poiFs.WriteFileSystem(out1);
            }

            /* Read the property Set streams from the POI filesystem just
             * Created. */
            POIFile[] psf2 = Util.ReadPropertySets(copy);
            for (int i = 0; i < psf2.Length; i++)
            {
                byte[] bytes1 = psf1[i].GetBytes();
                byte[] bytes2 = psf2[i].GetBytes();
                Stream in1 = new ByteArrayInputStream(bytes1);
                Stream in2 = new ByteArrayInputStream(bytes2);
                PropertySet ps1 = PropertySetFactory.Create(in1);
                PropertySet ps2 = PropertySetFactory.Create(in2);

                /* Compare the property Set stream with the corresponding one
                 * from the origin file and check whether they are equal. */
                
                Assert.AreEqual(ps1, ps2, "Equality for file " + f.Name);
            }
            out1.Close();
        }
コード例 #9
0
ファイル: TestWrite.cs プロジェクト: xoposhiy/npoi
        public void TestWriteTwoSections()
        {
            String STREAM_NAME = "PropertySetStream";
            String SECTION1 = "Section 1";
            String SECTION2 = "Section 2";

            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite);
            //filename.deleteOnExit();
            FileStream out1 = file;

            POIFSFileSystem poiFs = new POIFSFileSystem();
            MutablePropertySet ps = new MutablePropertySet();
            ps.ClearSections();

            ClassID formatID = new ClassID();
            formatID.Bytes = new byte[]{0, 1,  2,  3,  4,  5,  6,  7,
                                     8, 9, 10, 11, 12, 13, 14, 15};
            MutableSection s1 = new MutableSection();
            s1.SetFormatID(formatID);
            s1.SetProperty(2, SECTION1);
            ps.AddSection(s1);

            MutableSection s2 = new MutableSection();
            s2.SetFormatID(formatID);
            s2.SetProperty(2, SECTION2);
            ps.AddSection(s2);

            poiFs.CreateDocument(ps.GetStream(), STREAM_NAME);
            poiFs.WriteFileSystem(out1);
            //out1.Close();

            /* Read the POIFS: */
            psa = new PropertySet[1];
            POIFSReader reader2 = new POIFSReader();
            //reader2.StreamReaded += new POIFSReaderEventHandler(reader2_StreamReaded);
            POIFSReaderListener2 prl = new POIFSReaderListener2();
            reader2.RegisterListener(prl);
            reader2.Read(file);
            Assert.IsNotNull(psa[0]);
            Section s = (Section)(psa[0].Sections[0]);
            Assert.AreEqual(s.FormatID, formatID);
            Object p = s.GetProperty(2);
            Assert.AreEqual(SECTION1, p);
            s = (Section)(psa[0].Sections[1]);
            p = s.GetProperty(2);
            Assert.AreEqual(SECTION2, p);

            file.Close();
            //File.Delete(dataDir + POI_FS);
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }
コード例 #10
0
ファイル: TestWrite.cs プロジェクト: xoposhiy/npoi
        public void TestWriteEmptyPropertySet()
        {
            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            using (FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite))
            {
                //filename.deleteOnExit();

                /* Create a mutable property Set and Write it to a POIFS: */
                FileStream out1 = file;
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps = new MutablePropertySet();
                MutableSection s = (MutableSection)ps.Sections[0];
                s.SetFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);

                MemoryStream psStream = new MemoryStream();
                ps.Write(psStream);
                psStream.Close();
                byte[] streamData = psStream.ToArray();
                poiFs.CreateDocument(new MemoryStream(streamData),
                                     SummaryInformation.DEFAULT_STREAM_NAME);
                poiFs.WriteFileSystem(out1);
                //out1.Close();
                file.Position = 0;
                /* Read the POIFS: */
                POIFSReader reader3 = new POIFSReader();
                reader3.StreamReaded += new POIFSReaderEventHandler(reader3_StreamReaded);
                reader3.Read(file);
                file.Close();
                //File.Delete(dataDir + POI_FS);
            }
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }
コード例 #11
0
ファイル: TestWrite.cs プロジェクト: xoposhiy/npoi
        public void TestNoFormatID()
        {
            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            using (FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite))
            {
                //FileStream filename = File.OpenRead(dataDir + POI_FS);
                //filename.deleteOnExit();

                /* Create a mutable property Set with a section that does not have the
                 * formatID Set: */
                FileStream out1 = file;
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps = new MutablePropertySet();
                ps.ClearSections();
                ps.AddSection(new MutableSection());

                /* Write it to a POIFS and the latter to disk: */
                try
                {
                    MemoryStream psStream = new MemoryStream();
                    ps.Write(psStream);
                    psStream.Close();
                    byte[] streamData = psStream.ToArray();
                    poiFs.CreateDocument(new MemoryStream(streamData),
                                         SummaryInformation.DEFAULT_STREAM_NAME);
                    poiFs.WriteFileSystem(out1);
                    out1.Close();
                    Assert.Fail("Should have thrown a NoFormatIDException.");
                }
                catch (Exception ex)
                {
                    Assert.IsTrue(ex is NoFormatIDException);
                }
                finally
                {
                    out1.Close();
                }
            }
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }
コード例 #12
0
ファイル: HSSFWorkbook.cs プロジェクト: xiepeixing/npoi
        /// <summary>
        /// Write out this workbook to an Outputstream.  Constructs
        /// a new POI POIFSFileSystem, passes in the workbook binary representation  and
        /// Writes it out.
        /// </summary>
        /// <param name="stream">the java OutputStream you wish to Write the XLS to</param>
        public override void Write(Stream stream)
        {
            byte[] bytes = GetBytes();
            POIFSFileSystem fs = new POIFSFileSystem();
            
            // For tracking what we've written out, used if we're
            //  going to be preserving nodes
            List<string> excepts = new List<string>(1);

            using (MemoryStream newMemoryStream = new MemoryStream(bytes))
            {
                // Write out the Workbook stream
                fs.CreateDocument(newMemoryStream, "Workbook");

                // Write out our HPFS properties, if we have them
                WriteProperties(fs, excepts);

                if (preserveNodes)
                {
                    // Don't Write out the old Workbook, we'll be doing our new one
                    excepts.Add("Workbook");
                    // If the file had WORKBOOK instead of Workbook, we'll Write it
                    //  out correctly shortly, so don't include the old one
                    excepts.Add("WORKBOOK");

                    // Copy over all the other nodes to our new poifs
                    POIUtils.CopyNodes(directory, fs.Root, excepts);
                    // YK: preserve StorageClsid, it is important for embedded workbooks,
                    // see Bugzilla 47920
                    fs.Root.StorageClsid = (this.directory.StorageClsid);
                }
                fs.WriteFileSystem(stream);

            }
            
            bytes = null;
        }
コード例 #13
0
ファイル: HSSFWorkbook.cs プロジェクト: hijson/npoi
        /// <summary>
        /// Write out this workbook to an Outputstream.  Constructs
        /// a new POI POIFSFileSystem, passes in the workbook binary representation  and
        /// Writes it out.
        /// </summary>
        /// <param name="stream">the java OutputStream you wish to Write the XLS to</param>
        public override void Write(Stream stream)
        {
            byte[] bytes = GetBytes();
            POIFSFileSystem fs = new POIFSFileSystem();

            if (this.DocumentSummaryInformation == null)
            {
                this.DocumentSummaryInformation = HPSF.PropertySetFactory.CreateDocumentSummaryInformation();
            }
            NPOI.HPSF.CustomProperties cp = this.DocumentSummaryInformation.CustomProperties;
            if(cp==null)
            {
                cp= new NPOI.HPSF.CustomProperties();
            }
            cp.Put("Generator", "NPOI");
            cp.Put("Generator Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
            this.DocumentSummaryInformation.CustomProperties = cp;
            if (this.SummaryInformation == null)
            {
                this.SummaryInformation = HPSF.PropertySetFactory.CreateSummaryInformation();
            }            
            this.SummaryInformation.ApplicationName = "NPOI";

            // For tracking what we've written out, used if we're
            //  going to be preserving nodes
            List<string> excepts = new List<string>(1);

            using (MemoryStream newMemoryStream = new MemoryStream(bytes))
            {
                // Write out the Workbook stream
                fs.CreateDocument(newMemoryStream, "Workbook");

                // Write out our HPFS properties, if we have them
                WriteProperties(fs, excepts);

                if (preserveNodes)
                {
                    // Don't Write out the old Workbook, we'll be doing our new one
                    // If the file had an "incorrect" name for the workbook stream,
                    // don't write the old one as we'll use the correct name shortly
                    excepts.AddRange(WORKBOOK_DIR_ENTRY_NAMES);

                    // Copy over all the other nodes to our new poifs
                    EntryUtils.CopyNodes(
                            new FilteringDirectoryNode(this.directory, excepts)
                            , new FilteringDirectoryNode(fs.Root, excepts)
                    );
                    // YK: preserve StorageClsid, it is important for embedded workbooks,
                    // see Bugzilla 47920
                    fs.Root.StorageClsid = (this.directory.StorageClsid);
                }
                fs.WriteFileSystem(stream);

            }
            
            bytes = null;
        }
コード例 #14
0
ファイル: HSSFWorkbook.cs プロジェクト: ChiangHanLung/PIC_VDS
        /// <summary>
        /// Write out this workbook to an Outputstream.  Constructs
        /// a new POI POIFSFileSystem, passes in the workbook binary representation  and
        /// Writes it out.
        /// </summary>
        /// <param name="stream">the java OutputStream you wish to Write the XLS to</param>
        public override void Write(Stream stream)
        {
            byte[] bytes = GetBytes();
            POIFSFileSystem fs = new POIFSFileSystem();
            // For tracking what we've written out, used if we're
            //  going to be preserving nodes
            IList excepts = new ArrayList(1);

            // Write out the Workbook stream
            fs.CreateDocument(new MemoryStream(bytes), "Workbook");

            // Write out our HPFS properties, if we have them
            WriteProperties(fs, excepts);

            if (preserveNodes)
            {
                // Don't Write out the old Workbook, we'll be doing our new one
                excepts.Add("Workbook");
                // If the file had WORKBOOK instead of Workbook, we'll Write it
                //  out correctly shortly, so don't include the old one
                excepts.Add("WORKBOOK");

                // Copy over all the other nodes to our new poifs
                CopyNodes(this.filesystem, fs, excepts);
            }
            fs.WriteFileSystem(stream);
        }
コード例 #15
0
ファイル: TestRecordFactory.cs プロジェクト: 89sos98/npoi
        public void TestNonZeroPadding_bug46987()
        {
            Record[] recs = {
			    new BOFRecord(),
			    new WriteAccessRecord(), // need *something* between BOF and EOF
			    EOFRecord.instance,
			    BOFRecord.CreateSheetBOF(),
			    EOFRecord.instance,
		    };
            MemoryStream baos = new MemoryStream();
            for (int i = 0; i < recs.Length; i++)
            {
                byte[] data = recs[i].Serialize();
                baos.Write(data,0,data.Length);
            }
            //simulate the bad padding at the end of the workbook stream in attachment 23483 of bug 46987
            baos.WriteByte(0x00);
            baos.WriteByte(0x11);
            baos.WriteByte(0x00);
            baos.WriteByte(0x02);
            for (int i = 0; i < 192; i++)
            {
                baos.WriteByte(0x00);
            }


            POIFSFileSystem fs = new POIFSFileSystem();
            Stream is1;
            fs.CreateDocument(new MemoryStream(baos.ToArray()), "dummy");
            is1 = fs.Root.CreatePOIFSDocumentReader("dummy");


            List<Record> outRecs;
            try
            {
                outRecs = RecordFactory.CreateRecords(is1);
            }
            catch (Exception e)
            {
                if (e.Message.Equals("Buffer underrun - requested 512 bytes but 192 was available"))
                {
                    throw new AssertionException("Identified bug 46987");
                }
                throw e;
            }
            Assert.AreEqual(5, outRecs.Count);
        }
コード例 #16
0
ファイル: TestWrite.cs プロジェクト: xoposhiy/npoi
        public void TestWriteSimplePropertySet()
        {
            String AUTHOR = "Rainer Klute";
            String TITLE = "Test Document";

            FileInfo fi = TempFile.CreateTempFile(POI_FS, ".doc");
            FileStream file = new FileStream(fi.FullName, FileMode.Open, FileAccess.ReadWrite);

            FileStream out1 = file;
            POIFSFileSystem poiFs = new POIFSFileSystem();

            MutablePropertySet ps = new MutablePropertySet();
            MutableSection si = new MutableSection();
            si.SetFormatID(SectionIDMap.SUMMARY_INFORMATION_ID);
            ps.Sections[0] = si;

            MutableProperty p = new MutableProperty();
            p.ID = PropertyIDMap.PID_AUTHOR;
            p.Type = Variant.VT_LPWSTR;
            p.Value = AUTHOR;
            si.SetProperty(p);
            si.SetProperty(PropertyIDMap.PID_TITLE, Variant.VT_LPSTR, TITLE);

            poiFs.CreateDocument(ps.GetStream(),
                                 SummaryInformation.DEFAULT_STREAM_NAME);
            poiFs.WriteFileSystem(out1);
            //out1.Close();
            file.Position = 0;

            POIFSReader reader1 = new POIFSReader();
            //reader1.StreamReaded += new POIFSReaderEventHandler(reader1_StreamReaded);
            POIFSReaderListener1 psl = new POIFSReaderListener1();
            reader1.RegisterListener(psl);
            reader1.Read(file);
            Assert.IsNotNull(psa[0]);
            Assert.IsTrue(psa[0].IsSummaryInformation);

            Section s = (Section)(psa[0].Sections[0]);
            Object p1 = s.GetProperty(PropertyIDMap.PID_AUTHOR);
            Object p2 = s.GetProperty(PropertyIDMap.PID_TITLE);
            Assert.AreEqual(AUTHOR, p1);
            Assert.AreEqual(TITLE, p2);
            file.Close();
            try
            {
                File.Delete(fi.FullName);
            }
            catch
            {
            }
        }
コード例 #17
0
ファイル: POIDocument.cs プロジェクト: ChiangHanLung/PIC_VDS
        /// <summary>
        /// Writes out a given ProperySet
        /// </summary>
        /// <param name="name">the (POIFS Level) name of the property to Write.</param>
        /// <param name="Set">the PropertySet to Write out.</param>
        /// <param name="outFS">the POIFSFileSystem to Write the property into.</param>
        protected void WritePropertySet(String name, PropertySet Set, POIFSFileSystem outFS)
        {
            try
            {
                MutablePropertySet mSet = new MutablePropertySet(Set);
                MemoryStream bOut = new MemoryStream();

                mSet.Write(bOut);
                byte[] data = bOut.ToArray();
                MemoryStream bIn = new MemoryStream(data);
                outFS.CreateDocument(bIn, name);

                //logger.Log(POILogger.INFO, "Wrote property Set " + name + " of size " + data.Length);
            }
            catch (WritingNotSupportedException)
            {
                Console.Error.WriteLine("Couldn't Write property Set with name " + name + " as not supported by HPSF yet");
            }
        }
コード例 #18
0
ファイル: TestWrite.cs プロジェクト: Reinakumiko/npoi
        public void TestDictionaryWithInvalidCodepage()
        {

            using (FileStream copy = File.Create(@".\Test-HPSF.ole2"))
            {
                /* Write: */
                POIFSFileSystem poiFs = new POIFSFileSystem();
                MutablePropertySet ps1 = new MutablePropertySet();
                MutableSection s = (MutableSection)ps1.Sections[0];
                Hashtable m = new Hashtable(3, 1.0f);
                m[1] = "String 1";
                m[2] = "String 2";
                m[3] = "String 3";

                try
                {
                    s.Dictionary = m;
                    s.SetFormatID(SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1);
                    s.SetProperty(PropertyIDMap.PID_CODEPAGE, Variant.VT_I2, 12345);
                    poiFs.CreateDocument(ps1.ToInputStream(), "Test");
                    poiFs.WriteFileSystem(copy);
                    Assert.Fail("This Testcase did not detect the invalid codepage value.");
                }
                catch (IllegalPropertySetDataException)
                {
                        
                    Assert.IsTrue(true);
                }
            }
            
            
            
            if (File.Exists(@".\Test-HPSF.ole2"))
            {
                File.Delete(@".\Test-HPSF.ole2");
            }
        }