Ejemplo n.º 1
0
        public void TestAreDirectoriesIdentical()
        {
            POIFSFileSystem fs   = new POIFSFileSystem();
            DirectoryEntry  dirA = fs.CreateDirectory("DirA");
            DirectoryEntry  dirB = fs.CreateDirectory("DirB");

            // Names must match
            Assert.AreEqual(false, EntryUtils.AreDirectoriesIdentical(dirA, dirB));

            // Empty dirs are fine
            DirectoryEntry dirA1 = dirA.CreateDirectory("TheDir");
            DirectoryEntry dirB1 = dirB.CreateDirectory("TheDir");

            Assert.AreEqual(0, dirA1.EntryCount);
            Assert.AreEqual(0, dirB1.EntryCount);
            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(dirA1, dirB1));

            // Otherwise children must match
            dirA1.CreateDocument("Entry1", new ByteArrayInputStream(dataSmallA));
            Assert.AreEqual(false, EntryUtils.AreDirectoriesIdentical(dirA1, dirB1));

            dirB1.CreateDocument("Entry1", new ByteArrayInputStream(dataSmallA));
            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(dirA1, dirB1));

            dirA1.CreateDirectory("DD");
            Assert.AreEqual(false, EntryUtils.AreDirectoriesIdentical(dirA1, dirB1));
            dirB1.CreateDirectory("DD");
            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(dirA1, dirB1));


            // Excludes support
            List <String>          excl = new List <string>(new String[] { "Ignore1", "IgnDir/Ign2" });
            FilteringDirectoryNode fdA  = new FilteringDirectoryNode(dirA1, excl);
            FilteringDirectoryNode fdB  = new FilteringDirectoryNode(dirB1, excl);

            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(fdA, fdB));

            // Add an ignored doc, no notice is taken
            fdA.CreateDocument("Ignore1", new ByteArrayInputStream(dataSmallA));
            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(fdA, fdB));

            // Add a directory with filtered contents, not the same
            DirectoryEntry dirAI = dirA1.CreateDirectory("IgnDir");

            Assert.AreEqual(false, EntryUtils.AreDirectoriesIdentical(fdA, fdB));

            DirectoryEntry dirBI = dirB1.CreateDirectory("IgnDir");

            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(fdA, fdB));

            // Add something to the filtered subdir that gets ignored
            dirAI.CreateDocument("Ign2", new ByteArrayInputStream(dataSmallA));
            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(fdA, fdB));

            // And something that doesn't
            dirAI.CreateDocument("IgnZZ", new ByteArrayInputStream(dataSmallA));
            Assert.AreEqual(false, EntryUtils.AreDirectoriesIdentical(fdA, fdB));

            dirBI.CreateDocument("IgnZZ", new ByteArrayInputStream(dataSmallA));
            Assert.AreEqual(true, EntryUtils.AreDirectoriesIdentical(fdA, fdB));
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Creates a new XLS -> strings converter
 /// </summary>
 /// <param name="fs">The POIFSFileSystem to process</param>
 public Xls2Strings(POIFSFileSystem fs)
 {
     _fs = fs;
 }
Ejemplo n.º 3
0
        public static void AddExcel(List <T> lists, string workbookFile, string SheetNumber, float MaxPressure)
        {
            try
            {
                int             sheetflat = -1;
                FileStream      fs        = new FileStream(workbookFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取流
                POIFSFileSystem ps        = new POIFSFileSystem(fs);
                fs.Close();

                FileStream   fout     = new FileStream(workbookFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);//写入流
                HSSFWorkbook workbook = new HSSFWorkbook(ps);
                HSSFSheet    sheet    = null;
                for (int i = 0; i < workbook.NumberOfSheets; i++)
                {
                    if (SheetNumber == workbook.GetSheetName(i))
                    {
                        sheetflat = i;
                    }
                }
                if (sheetflat != -1)
                {
                    sheet = workbook.GetSheetAt(sheetflat) as HSSFSheet;    //如果已经有了就先清空该sheet
                    for (int i = 0; i < sheet.LastRowNum + 1; i++)
                    {
                        HSSFRow row = sheet.GetRow(i) as HSSFRow;
                        row.CreateCell(0).SetCellValue("");
                        row.CreateCell(1).SetCellValue("");
                    }
                }
                else
                {
                    sheet = workbook.CreateSheet(SheetNumber) as HSSFSheet;
                }

                HSSFRow        HeadRow    = sheet.CreateRow(0) as HSSFRow;
                bool           h          = false;
                int            j          = 1;
                Type           type       = typeof(T);
                PropertyInfo[] properties = type.GetProperties(); //获得类中的各个属性,添到表单中
                foreach (T item in lists)                         //泛型的类
                {
                    HSSFRow dataRow = sheet.CreateRow(j) as HSSFRow;
                    int     i       = 0;
                    foreach (PropertyInfo column in properties)
                    {
                        if (!h)
                        {
                            HeadRow.CreateCell(i).SetCellValue(column.Name);    //在第一行数据前加入列标签
                            HeadRow.CreateCell(2).SetCellValue("MaxPressure");
                            if (i == 0)
                            {
                                dataRow.CreateCell(i).SetCellValue(column.GetValue(item, null) == null ? "" :
                                                                   (Convert.ToInt16(column.GetValue(item, null)) * Global.SystemPara.con_factor_x).ToString("000.0"));
                            }
                            else
                            {
                                dataRow.CreateCell(i).SetCellValue(column.GetValue(item, null) == null ? "" :
                                                                   (Convert.ToInt16(column.GetValue(item, null)) * Global.SystemPara.con_factor_y).ToString("00.00"));
                                dataRow.CreateCell(2).SetCellValue(MaxPressure.ToString("00.00"));
                            }
                        }
                        else
                        {
                            if (i == 0)
                            {
                                dataRow.CreateCell(i).SetCellValue(column.GetValue(item, null) == null ? "" :
                                                                   (Convert.ToInt16(column.GetValue(item, null)) * Global.SystemPara.con_factor_x).ToString("000.0"));
                            }
                            else
                            {
                                dataRow.CreateCell(i).SetCellValue(column.GetValue(item, null) == null ? "" :
                                                                   (Convert.ToInt16(column.GetValue(item, null)) * Global.SystemPara.con_factor_y).ToString("00.00"));
                            }
                        }
                        i++;
                    }
                    h = true;
                    j++;
                }
                fout.Flush();
                workbook.Write(fout);    //写入文件
                workbook = null;
                fout.Close();
            }
            catch (Exception e)
            {
                // ReadValue.logNet.WriteError($"数据保存到Excel失败,错误编号{e.Message}");
            }
        }
Ejemplo n.º 4
0
 public HPSFPropertiesExtractor(POIFSFileSystem fs)
     : base(new PropertiesOnlyDocument(fs))
 {
 }
Ejemplo n.º 5
0
        public void TestReadDocumentSummaryInformation()
        {
            POIDataSamples _samples = POIDataSamples.GetHPSFInstance();

            string[] files = _samples.GetFiles("Test*.*");

            for (int i = 0; i < files.Length; i++)
            {
                if (!TestReadAllFiles.checkExclude(files[i]))
                {
                    continue;
                }
                using (FileStream doc = new FileStream(files[i], FileMode.Open, FileAccess.Read))
                {
                    Console.WriteLine("Reading file " + doc);
                    try
                    {
                        /* Read a Test document <em>doc</em> into a POI filesystem. */
                        POIFSFileSystem poifs    = new POIFSFileSystem(doc);
                        DirectoryEntry  dir      = poifs.Root;
                        DocumentEntry   dsiEntry = null;
                        try
                        {
                            dsiEntry = (DocumentEntry)dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
                        }
                        catch (FileNotFoundException)
                        {
                            /*
                             * A missing document summary information stream is not an error
                             * and therefore silently ignored here.
                             */
                        }
                        //catch (System.IO.IOException ex)
                        //{
                        //     // The process cannot access the file 'testcases\test-data\hpsf\TestUnicode.xls' because it is being used by another process.
                        //    Console.Error.WriteLine("Exception ignored (because some other test cases may read this file, too): " + ex.Message);
                        //}

                        /*
                         * If there is a document summry information stream, Read it from
                         * the POI filesystem.
                         */
                        if (dsiEntry != null)
                        {
                            DocumentInputStream        dis = new DocumentInputStream(dsiEntry);
                            PropertySet                ps  = new PropertySet(dis);
                            DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps);

                            /* Execute the Get... methods. */
                            Console.WriteLine(dsi.ByteCount);
                            Console.WriteLine(dsi.ByteOrder);
                            Console.WriteLine(dsi.Category);
                            Console.WriteLine(dsi.Company);
                            Console.WriteLine(dsi.CustomProperties);
                            // FIXME Console.WriteLine(dsi.Docparts);
                            // FIXME Console.WriteLine(dsi.HeadingPair);
                            Console.WriteLine(dsi.HiddenCount);
                            Console.WriteLine(dsi.LineCount);
                            Console.WriteLine(dsi.LinksDirty);
                            Console.WriteLine(dsi.Manager);
                            Console.WriteLine(dsi.MMClipCount);
                            Console.WriteLine(dsi.NoteCount);
                            Console.WriteLine(dsi.ParCount);
                            Console.WriteLine(dsi.PresentationFormat);
                            Console.WriteLine(dsi.Scale);
                            Console.WriteLine(dsi.SlideCount);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new IOException("While handling file " + files[i], e);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        public void AgileEncryption()
        {
            int maxKeyLen = Cipher.GetMaxAllowedKeyLength("AES");

            Assume.That(maxKeyLen == 2147483647, "Please install JCE Unlimited Strength Jurisdiction Policy files for AES 256");

            FileStream       file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-pass.docx");
            String           pass = "******";
            NPOIFSFileSystem nfs  = new NPOIFSFileSystem(file);

            // Check the encryption details
            EncryptionInfo infoExpected = new EncryptionInfo(nfs);
            Decryptor      decExpected  = Decryptor.GetInstance(infoExpected);
            bool           passed       = decExpected.VerifyPassword(pass);

            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            Stream is1 = decExpected.GetDataStream(nfs);

            byte[] payloadExpected = IOUtils.ToByteArray(is1);
            is1.Close();

            long decPackLenExpected = decExpected.GetLength();

            Assert.AreEqual(decPackLenExpected, payloadExpected.Length);

            is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
            ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
            ///throw new NotImplementedException(BoundedInputStream);
            byte[] encPackExpected = IOUtils.ToByteArray(is1);
            is1.Close();

            // listDir(nfs.Root, "orig", "");

            nfs.Close();

            // check that same verifier/salt lead to same hashes
            byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
            byte[] verifierExpected     = decExpected.GetVerifier();
            byte[] keySalt       = infoExpected.Header.KeySalt;
            byte[] keySpec       = decExpected.GetSecretKey().GetEncoded();
            byte[] integritySalt = decExpected.GetIntegrityHmacKey();
            // the hmacs of the file always differ, as we use PKCS5-pAdding to pad the bytes
            // whereas office just uses random bytes
            // byte integrityHash[] = d.IntegrityHmacValue;

            POIFSFileSystem fs         = new POIFSFileSystem();
            EncryptionInfo  infoActual = new EncryptionInfo(
                EncryptionMode.Agile
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            Encryptor e = Encryptor.GetInstance(infoActual);

            e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, integritySalt);

            Stream os = e.GetDataStream(fs);

            IOUtils.Copy(new MemoryStream(payloadExpected), os);
            os.Close();

            MemoryStream bos = new MemoryStream();

            fs.WriteFileSystem(bos);

            nfs        = new NPOIFSFileSystem(new MemoryStream(bos.ToArray()));
            infoActual = new EncryptionInfo(nfs.Root);
            Decryptor decActual = Decryptor.GetInstance(infoActual);

            passed = decActual.VerifyPassword(pass);
            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            is1 = decActual.GetDataStream(nfs);
            byte[] payloadActual = IOUtils.ToByteArray(is1);
            is1.Close();

            long decPackLenActual = decActual.GetLength();

            is1 = nfs.Root.CreateDocumentInputStream(Decryptor.DEFAULT_POIFS_ENTRY);
            ///is1 = new BoundedInputStream(is1, is1.Available() - 16); // ignore pAdding block
            ///throw new NotImplementedException(BoundedInputStream);
            byte[] encPackActual = IOUtils.ToByteArray(is1);
            is1.Close();

            // listDir(nfs.Root, "copy", "");

            nfs.Close();

            AgileEncryptionHeader aehExpected = (AgileEncryptionHeader)infoExpected.Header;
            AgileEncryptionHeader aehActual   = (AgileEncryptionHeader)infoActual.Header;

            CollectionAssert.AreEqual(aehExpected.GetEncryptedHmacKey(), aehActual.GetEncryptedHmacKey());
            Assert.AreEqual(decPackLenExpected, decPackLenActual);
            CollectionAssert.AreEqual(payloadExpected, payloadActual);
            CollectionAssert.AreEqual(encPackExpected, encPackActual);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExcelExtractor"/> class.
 /// </summary>
 /// <param name="fs">The fs.</param>
 public ExcelExtractor(POIFSFileSystem fs)
     : this(new HSSFWorkbook(fs))
 {
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="POIDocument"/> class.
 /// </summary>
 /// <param name="fs">The fs.</param>
 public POIDocument(POIFSFileSystem fs)
     : this(fs.Root)
 {
 }
Ejemplo n.º 9
0
        public void TestAddToExistingSheet()
        {
            // dvEmpty.xls is a simple one sheet workbook.  With a DataValidations header record but no
            // DataValidations.  It's important that the example has one SHEETPROTECTION record.
            // Such a workbook can be Created in Excel (2007) by Adding datavalidation for one cell
            // and then deleting the row that Contains the cell.
            IWorkbook                 wb    = HSSFTestDataSamples.OpenSampleWorkbook("dvEmpty.xls");
            int                       dvRow = 0;
            ISheet                    sheet = wb.GetSheetAt(0);
            IDataValidationHelper     dataValidationHelper = sheet.GetDataValidationHelper();
            IDataValidationConstraint dc = dataValidationHelper.CreateintConstraint(OperatorType.EQUAL, "42", null);
            IDataValidation           dv = dataValidationHelper.CreateValidation(dc, new CellRangeAddressList(dvRow, dvRow, 0, 0));

            dv.EmptyCellAllowed = (/*setter*/ false);
            dv.ErrorStyle       = (/*setter*/ ERRORSTYLE.STOP);
            dv.ShowPromptBox    = (/*setter*/ true);
            dv.CreateErrorBox("Xxx", "Yyy");
            dv.SuppressDropDownArrow = (/*setter*/ true);

            sheet.AddValidationData(dv);

            MemoryStream baos = new MemoryStream();

            try
            {
                wb.Write(baos);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }

            byte[] wbData = baos.ToArray();

#if !HIDE_UNREACHABLE_CODE
            if (false)
            {                                          // TODO (Jul 2008) fix EventRecordFactory to process unknown records, (and DV records for that matter)
                ERFListener        erfListener = null; // new MyERFListener();
                EventRecordFactory erf         = new EventRecordFactory(erfListener, null);
                try
                {
                    POIFSFileSystem fs = new POIFSFileSystem(new MemoryStream(baos.ToArray()));
                    throw new NotImplementedException("The method CreateDocumentInputStream of POIFSFileSystem is not implemented.");
                    //erf.ProcessRecords(fs.CreateDocumentInputStream("Workbook"));
                }
                catch (RecordFormatException e)
                {
                    throw new RuntimeException(e);
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
            }
            // else verify record ordering by navigating the raw bytes
#endif

            byte[] dvHeaderRecStart = { (byte)0xB2, 0x01, 0x12, 0x00, };
            int    dvHeaderOffset   = FindIndex(wbData, dvHeaderRecStart);
            Assert.IsTrue(dvHeaderOffset > 0);
            int nextRecIndex = dvHeaderOffset + 22;
            int nextSid
                = ((wbData[nextRecIndex + 0] << 0) & 0x00FF)
                  + ((wbData[nextRecIndex + 1] << 8) & 0xFF00)
                ;
            // nextSid should be for a DVRecord.  If anything comes between the DV header record
            // and the DV records, Excel will not be able to open the workbook without error.

            if (nextSid == 0x0867)
            {
                throw new AssertionException("Identified bug 45519");
            }
            Assert.AreEqual(DVRecord.sid, nextSid);
        }
Ejemplo n.º 10
0
 public EncryptionInfo(POIFSFileSystem fs)
     : this(fs.Root)
 {
 }
Ejemplo n.º 11
0
        /// <summary>
        /// 根据数据实体和配置生成相应的Excel文件
        /// </summary>
        /// <param name="sourceData">数据源</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public string CreateExcelFile(IList sourceData, string fileName)
        {
            //获取列表第一个元素的数据类型
            Type type = null;

            if (sourceData.Count > 0)
            {
                type = sourceData[0].GetType();
            }

            //创建2007的Excel
            HSSFWorkbook workbook = null;

            //如果文件存在,则直接获取采用追加的方式追加进去
            string filePath = GetDownloadPath(fileName);

            string absFilePath = FileUtils.GetPhysicalPath(filePath);

            ISheet sheet = null;

            IRow row = null;

            //如果已经存在该文件,则说明已经产生过了,那么采用追加的方式
            if (File.Exists(absFilePath))
            {
                using (var fs = new FileStream(absFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    POIFSFileSystem ps = new POIFSFileSystem(fs);

                    workbook = new HSSFWorkbook(ps);

                    sheet = workbook.GetSheetAt(0);

                    fs.Close();
                    fs.Dispose();
                    //row = sheet.CreateRow(sheet.LastRowNum + 1);
                }//读取流
            }
            else
            {
                // (absFilePath);
                workbook = new HSSFWorkbook();

                sheet = workbook.CreateSheet();

                //设置标题列样式
                ICellStyle headStyle = workbook.CreateCellStyle();
                headStyle.VerticalAlignment = VerticalAlignment.Center;
                headStyle.Alignment         = HorizontalAlignment.Center;

                //设置字体-加粗字体
                IFont headFont = workbook.CreateFont();
                headFont.IsBold = true;

                row = sheet.CreateRow(0);

                //创建标题列
                for (int i = 0; i < this.Properties.Count; i++)
                {
                    var cell = row.CreateCell(i);
                    cell.SetCellValue(this.Properties[i].Caption);
                    cell.CellStyle = headStyle;
                    cell.CellStyle.SetFont(headFont);
                }
            }


            //创建内容列
            for (int i = 0; i < sourceData.Count; i++)
            {
                var entity = sourceData[i];
                //创建新的内容行
                row = sheet.CreateRow(i + sheet.LastRowNum + 1);

                //根据配置的属性列创建对应单元格
                for (int j = 0; j < this.Properties.Count; j++)
                {
                    var prop = this.Properties[j].EntityProp;

                    //储存内容值
                    object value = null;

                    //检查是否存在,如果存在则表示是拼接数据
                    if (prop.IndexOf("+", StringComparison.Ordinal) > -1)
                    {
                        var joinProps = prop.Split('+');
                        for (int jp = 0; jp < joinProps.Length; jp++)
                        {
                            var jprop    = joinProps[jp];
                            var newValue = this.GetPropValue(jprop, type, entity);
                            if (value != null)
                            {
                                if (newValue != null)
                                {
                                    //这里只智齿字符串的累加,主要解决地址合并省市区的情况
                                    value = value.ToString() + this.Properties[j].JoinPropChar + newValue.ToString();
                                }
                            }
                            else
                            {
                                value = newValue;
                            }
                        }
                    }
                    else
                    {
                        value = this.GetPropValue(prop, type, entity);
                    }

                    //根据数据类型填写对应的单元格
                    if (value == null)
                    {
                        row.CreateCell(j).SetCellValue("");
                    }
                    else if (value is int)
                    {
                        row.CreateCell(j).SetCellValue((int)value);
                    }
                    else if (value is long)
                    {
                        row.CreateCell(j).SetCellValue((long)value);
                    }
                    else if (value is decimal)
                    {
                        row.CreateCell(j).SetCellValue(Convert.ToDouble(value));
                    }
                    else if (value is double)
                    {
                        row.CreateCell(j).SetCellValue((double)value);
                    }
                    else if (value is DateTime)
                    {
                        row.CreateCell(j).SetCellValue(Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss.fff"));
                    }
                    else if (value is bool)
                    {
                        row.CreateCell(j).SetCellValue((bool)value);
                    }
                    else
                    {
                        row.CreateCell(j).SetCellValue(value.ToString());
                    }
                }
            }


            using (FileStream fs = File.OpenWrite(absFilePath))
            {
                workbook.Write(fs);
                fs.Close();
                fs.Dispose();
            }

            workbook = null;
            return(filePath);
        }
Ejemplo n.º 12
0
        public void TestReallyEmbedSomething()
        {
            HSSFWorkbook  wb        = new HSSFWorkbook();
            ISheet        sheet     = wb.CreateSheet();
            HSSFPatriarch patriarch = sheet.CreateDrawingPatriarch() as HSSFPatriarch;

            byte[]          pictureData = HSSFTestDataSamples.GetTestDataFileContent("logoKarmokar4.png");
            byte[]          picturePPT  = POIDataSamples.GetSlideShowInstance().ReadFile("clock.jpg");
            int             imgIdx      = wb.AddPicture(pictureData, PictureType.PNG);
            POIFSFileSystem pptPoifs    = GetSamplePPT();
            int             pptIdx      = wb.AddOlePackage(pptPoifs, "Sample-PPT", "sample.ppt", "sample.ppt");
            POIFSFileSystem xlsPoifs    = GetSampleXLS();
            int             imgPPT      = wb.AddPicture(picturePPT, PictureType.JPEG);
            int             xlsIdx      = wb.AddOlePackage(xlsPoifs, "Sample-XLS", "sample.xls", "sample.xls");
            int             txtIdx      = wb.AddOlePackage(GetSampleTXT(), "Sample-TXT", "sample.txt", "sample.txt");

            int rowoffset = 5;
            int coloffset = 5;

            ICreationHelper  ch     = wb.GetCreationHelper();
            HSSFClientAnchor anchor = (HSSFClientAnchor)ch.CreateClientAnchor();

            anchor.SetAnchor((short)(2 + coloffset), 1 + rowoffset, 0, 0, (short)(3 + coloffset), 5 + rowoffset, 0, 0);
            anchor.AnchorType = (/*setter*/ AnchorType.DontMoveAndResize);

            patriarch.CreateObjectData(anchor, pptIdx, imgPPT);

            anchor = (HSSFClientAnchor)ch.CreateClientAnchor();
            anchor.SetAnchor((short)(5 + coloffset), 1 + rowoffset, 0, 0, (short)(6 + coloffset), 5 + rowoffset, 0, 0);
            anchor.AnchorType = (/*setter*/ AnchorType.DontMoveAndResize);

            patriarch.CreateObjectData(anchor, xlsIdx, imgIdx);

            anchor = (HSSFClientAnchor)ch.CreateClientAnchor();
            anchor.SetAnchor((short)(3 + coloffset), 10 + rowoffset, 0, 0, (short)(5 + coloffset), 11 + rowoffset, 0, 0);
            anchor.AnchorType = (/*setter*/ AnchorType.DontMoveAndResize);

            patriarch.CreateObjectData(anchor, txtIdx, imgIdx);

            anchor = (HSSFClientAnchor)ch.CreateClientAnchor();
            anchor.SetAnchor((short)(1 + coloffset), -2 + rowoffset, 0, 0, (short)(7 + coloffset), 14 + rowoffset, 0, 0);
            anchor.AnchorType = (/*setter*/ AnchorType.DontMoveAndResize);

            HSSFSimpleShape circle = patriarch.CreateSimpleShape(anchor);

            circle.ShapeType = (/*setter*/ HSSFSimpleShape.OBJECT_TYPE_OVAL);
            circle.IsNoFill  = (/*setter*/ true);

            if (false)
            {
                FileStream fos = new FileStream("embed.xls", FileMode.Create);
                wb.Write(fos);
                fos.Close();
            }

            wb = HSSFTestDataSamples.WriteOutAndReadBack(wb as HSSFWorkbook);

            MemoryStream   bos   = new MemoryStream();
            HSSFObjectData od    = wb.GetAllEmbeddedObjects()[0];
            Ole10Native    ole10 = Ole10Native.CreateFromEmbeddedOleObject((DirectoryNode)od.GetDirectory());

            bos = new MemoryStream();
            pptPoifs.WriteFileSystem(bos);
            Assert.IsTrue(Arrays.Equals(ole10.DataBuffer, bos.ToArray()));

            od    = wb.GetAllEmbeddedObjects()[1];
            ole10 = Ole10Native.CreateFromEmbeddedOleObject((DirectoryNode)od.GetDirectory());
            bos   = new MemoryStream();
            xlsPoifs.WriteFileSystem(bos);
            Assert.IsTrue(Arrays.Equals(ole10.DataBuffer, bos.ToArray()));

            od    = wb.GetAllEmbeddedObjects()[2];
            ole10 = Ole10Native.CreateFromEmbeddedOleObject((DirectoryNode)od.GetDirectory());
            Assert.IsTrue(Arrays.Equals(ole10.DataBuffer, GetSampleTXT()));
        }
Ejemplo n.º 13
0
 public void SetUp()
 {
     bout  = new MemoryStream();
     poifs = new POIFSFileSystem();
     dir   = poifs.Root;
     dsi   = null;
     try
     {
         DocumentEntry dsiEntry = (DocumentEntry)
                                  dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
         DocumentInputStream dis = new DocumentInputStream(dsiEntry);
         PropertySet         ps  = new PropertySet(dis);
         dis.Close();
         dsi = new DocumentSummaryInformation(ps);
     }
     catch (FileNotFoundException)
     {
         /* There is no document summary information yet. We have to Create a
          * new one. */
         dsi = PropertySetFactory.CreateDocumentSummaryInformation();
         Assert.IsNotNull(dsi);
     }
     catch (IOException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     catch (NoPropertySetStreamException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     catch (MarkUnsupportedException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     catch (UnexpectedPropertySetTypeException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     Assert.IsNotNull(dsi);
     try
     {
         DocumentEntry dsiEntry = (DocumentEntry)
                                  dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
         DocumentInputStream dis = new DocumentInputStream(dsiEntry);
         PropertySet         ps  = new PropertySet(dis);
         dis.Close();
         si = new SummaryInformation(ps);
     }
     catch (FileNotFoundException)
     {
         /* There is no document summary information yet. We have to Create a
          * new one. */
         si = PropertySetFactory.CreateSummaryInformation();
         Assert.IsNotNull(si);
     }
     catch (IOException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     catch (NoPropertySetStreamException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     catch (MarkUnsupportedException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     catch (UnexpectedPropertySetTypeException)
     {
         ////e.printStackTrace();
         Assert.Fail();
     }
     Assert.IsNotNull(dsi);
 }
Ejemplo n.º 14
0
        /**
         * Closes the MemoryStream and Reads it into a MemoryStream.
         * When finished writing information this method is used in the Tests to
         * start Reading from the Created document and then the see if the results match.
         *
         */
        private void CloseAndReOpen()
        {
            try
            {
                dsi.Write(dir, DocumentSummaryInformation.DEFAULT_STREAM_NAME);
                si.Write(dir, SummaryInformation.DEFAULT_STREAM_NAME);
            }
            catch (WritingNotSupportedException)
            {
                ////e.printStackTrace();
                Assert.Fail();
            }
            catch (IOException)
            {
                ////e.printStackTrace();
                Assert.Fail();
            }

            si  = null;
            dsi = null;
            try
            {
                poifs.WriteFileSystem(bout);
                bout.Flush();
            }
            catch (IOException)
            {
                ////e.printStackTrace();
                Assert.Fail();
            }

            Stream is1 = new MemoryStream(bout.ToArray());

            Assert.IsNotNull(is1);
            poifs = null;
            try
            {
                poifs = new POIFSFileSystem(is1);
            }
            catch (IOException)
            {
                ////e.printStackTrace();
                Assert.Fail();
            }
            try
            {
                is1.Close();
            }
            catch (IOException)
            {
                ////e.printStackTrace();
                Assert.Fail();
            }
            Assert.IsNotNull(poifs);
            /* Read the document summary information. */
            dir = poifs.Root;

            try
            {
                DocumentEntry dsiEntry = (DocumentEntry)
                                         dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);
                DocumentInputStream dis = new DocumentInputStream(dsiEntry);
                PropertySet         ps  = new PropertySet(dis);
                dis.Close();
                dsi = new DocumentSummaryInformation(ps);
            }
            catch (FileNotFoundException ex)
            {
                Assert.Fail(ex.Message);
            }
            catch (IOException e)
            {
                //e.printStackTrace();
                Assert.Fail(e.Message);
            }
            catch (NoPropertySetStreamException e)
            {
                //e.printStackTrace();
                Assert.Fail(e.Message);
            }
            catch (MarkUnsupportedException e)
            {
                //e.printStackTrace();
                Assert.Fail(e.Message);
            }
            catch (UnexpectedPropertySetTypeException e)
            {
                //e.printStackTrace();
                Assert.Fail(e.Message);
            }
            try
            {
                DocumentEntry dsiEntry = (DocumentEntry)
                                         dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
                DocumentInputStream dis = new DocumentInputStream(dsiEntry);
                PropertySet         ps  = new PropertySet(dis);
                dis.Close();
                si = new SummaryInformation(ps);
            }
            catch (FileNotFoundException)
            {
                /* There is no document summary information yet. We have to Create a
                 * new one. */
                si = PropertySetFactory.CreateSummaryInformation();
                Assert.IsNotNull(si);
            }
            catch (IOException)
            {
                //e.printStackTrace();
                Assert.Fail();
            }
            catch (NoPropertySetStreamException)
            {
                //e.printStackTrace();
                Assert.Fail();
            }
            catch (MarkUnsupportedException)
            {
                //e.printStackTrace();
                Assert.Fail();
            }
            catch (UnexpectedPropertySetTypeException)
            {
                //e.printStackTrace();
                Assert.Fail();
            }
        }
Ejemplo n.º 15
0
 public Stream GetDataStream(POIFSFileSystem fs)
 {
     return(GetDataStream(fs.Root));
 }
Ejemplo n.º 16
0
 public POIDocument(DirectoryNode dir, POIFSFileSystem fs)
 {
     directory = dir;
     //POILogFactory.GetLogger(this.GetType());
 }
Ejemplo n.º 17
0
 public EventBasedExcelExtractor(POIFSFileSystem fs)
     : base(null)
 {
     this.fs = fs;
 }
Ejemplo n.º 18
0
        public void TestWriteWellKnown1()
        {
            POIDataSamples _samples = POIDataSamples.GetHPSFInstance();

            using (FileStream doc1 = _samples.GetFile(POI_FS))
            {
                /* Read a Test document <em>doc1</em> into a POI filesystem. */
                POIFSFileSystem poifs    = new POIFSFileSystem(doc1);
                DirectoryEntry  dir      = poifs.Root;
                DocumentEntry   siEntry  = (DocumentEntry)dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
                DocumentEntry   dsiEntry = (DocumentEntry)dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

                /*
                 * Read the summary information stream and the document summary
                 * information stream from the POI filesystem.
                 *
                 * Please note that the result consists of SummaryInformation and
                 * DocumentSummaryInformation instances which are in memory only. To
                 * make them permanent they have to be written to a POI filesystem
                 * explicitly (overwriting the former contents). Then the POI filesystem
                 * should be saved to a file.
                 */
                DocumentInputStream dis = new DocumentInputStream(siEntry);
                PropertySet         ps  = new PropertySet(dis);
                SummaryInformation  si  = new SummaryInformation(ps);
                dis = new DocumentInputStream(dsiEntry);
                ps  = new PropertySet(dis);
                DocumentSummaryInformation dsi = new DocumentSummaryInformation(ps);

                /*
                 * Write all properties supported by HPSF to the summary information
                 * (e.g. author, edit date, application name) and to the document
                 * summary information (e.g. company, manager).
                 */
                Calendar cal = new GregorianCalendar();
                //long time1 = (long)cal.GetMilliseconds(new DateTime(2000, 6, 6, 6, 6, 6));

                //long time2 = (long)cal.GetMilliseconds(new DateTime(2001, 7, 7, 7, 7, 7));
                //long time3 = (long)cal.GetMilliseconds(new DateTime(2002, 8, 8, 8, 8, 8));

                int      nr = 4711;
                String   P_APPLICATION_NAME    = "Microsoft Office Word";
                String   P_AUTHOR              = "Rainer Klute";
                int      P_CHAR_COUNT          = 125;
                String   P_COMMENTS            = ""; //"Comments";
                DateTime P_CREATE_DATE_TIME    = new DateTime(2006, 2, 1, 7, 36, 0);
                long     P_EDIT_TIME           = ++nr * 1000 * 10;
                String   P_KEYWORDS            = "Test HPSF SummaryInformation DocumentSummaryInformation Writing";
                String   P_LAST_AUTHOR         = "LastAuthor";
                DateTime?P_LAST_PRINTED        = new DateTime(2001, 7, 7, 7, 7, 7);
                DateTime P_LAST_SAVE_DATE_TIME = new DateTime(2008, 9, 30, 9, 54, 0);
                int      P_PAGE_COUNT          = 1;
                String   P_REV_NUMBER          = "RevNumber";
                int      P_SECURITY            = 1;
                String   P_SUBJECT             = "Subject";
                String   P_TEMPLATE            = "Normal.dotm";
                // FIXME (byte array properties not yet implemented): byte[] P_THUMBNAIL = new byte[123];
                String P_TITLE      = "This document is used for testing POI HPSF¡¯s writing capabilities for the summary information stream and the document summary information stream";
                int    P_WORD_COUNT = 21;

                int    P_BYTE_COUNT = ++nr;
                String P_CATEGORY   = "Category";
                String P_COMPANY    = "Rainer Klute IT-Consulting GmbH";
                // FIXME (byte array properties not yet implemented): byte[]  P_DOCPARTS = new byte[123];
                // FIXME (byte array properties not yet implemented): byte[]  P_HEADING_PAIR = new byte[123];
                int      P_HIDDEN_COUNT        = ++nr;
                int      P_LINE_COUNT          = ++nr;
                bool     P_LINKS_DIRTY         = true;
                String   P_MANAGER             = "Manager";
                int      P_MM_CLIP_COUNT       = ++nr;
                int      P_NOTE_COUNT          = ++nr;
                int      P_PAR_COUNT           = ++nr;
                String   P_PRESENTATION_FORMAT = "PresentationFormat";
                bool     P_SCALE       = false;
                int      P_SLIDE_COUNT = ++nr;
                DateTime now           = DateTime.Now;

                int    POSITIVE_INTEGER = 2222;
                long   POSITIVE_LONG    = 3333;
                Double POSITIVE_DOUBLE  = 4444;
                int    NEGATIVE_INTEGER = 2222;
                long   NEGATIVE_LONG    = 3333;
                Double NEGATIVE_DOUBLE  = 4444;

                int    MAX_INTEGER = int.MaxValue;
                int    MIN_INTEGER = int.MinValue;
                long   MAX_LONG    = long.MaxValue;
                long   MIN_LONG    = long.MinValue;
                Double MAX_DOUBLE  = Double.MaxValue;
                Double MIN_DOUBLE  = Double.MinValue;

                si.ApplicationName  = P_APPLICATION_NAME;
                si.Author           = P_AUTHOR;
                si.CharCount        = P_CHAR_COUNT;
                si.Comments         = P_COMMENTS;
                si.CreateDateTime   = P_CREATE_DATE_TIME;
                si.EditTime         = P_EDIT_TIME;
                si.Keywords         = P_KEYWORDS;
                si.LastAuthor       = P_LAST_AUTHOR;
                si.LastPrinted      = P_LAST_PRINTED;
                si.LastSaveDateTime = P_LAST_SAVE_DATE_TIME;
                si.PageCount        = P_PAGE_COUNT;
                si.RevNumber        = P_REV_NUMBER;
                si.Security         = P_SECURITY;
                si.Subject          = P_SUBJECT;
                si.Template         = P_TEMPLATE;
                // FIXME (byte array properties not yet implemented): si.Thumbnail=P_THUMBNAIL;
                si.Title     = P_TITLE;
                si.WordCount = P_WORD_COUNT;

                dsi.ByteCount = P_BYTE_COUNT;
                dsi.Category  = P_CATEGORY;
                dsi.Company   = P_COMPANY;
                // FIXME (byte array properties not yet implemented): dsi.Docparts=P_DOCPARTS;
                // FIXME (byte array properties not yet implemented): dsi.HeadingPair=P_HEADING_PAIR;
                dsi.HiddenCount        = P_HIDDEN_COUNT;
                dsi.LineCount          = P_LINE_COUNT;
                dsi.LinksDirty         = P_LINKS_DIRTY;
                dsi.Manager            = P_MANAGER;
                dsi.MMClipCount        = P_MM_CLIP_COUNT;
                dsi.NoteCount          = P_NOTE_COUNT;
                dsi.ParCount           = P_PAR_COUNT;
                dsi.PresentationFormat = P_PRESENTATION_FORMAT;
                dsi.Scale      = P_SCALE;
                dsi.SlideCount = P_SLIDE_COUNT;

                CustomProperties customProperties = dsi.CustomProperties;
                if (customProperties == null)
                {
                    customProperties = new CustomProperties();
                }
                customProperties.Put("Schlüssel 1", "Wert 1");
                customProperties.Put("Schlüssel 2", "Wert 2");
                customProperties.Put("Schlüssel 3", "Wert 3");
                customProperties.Put("Schlüssel 4", "Wert 4");
                customProperties.Put("positive_int", POSITIVE_INTEGER);
                customProperties.Put("positive_long", POSITIVE_LONG);
                customProperties.Put("positive_Double", POSITIVE_DOUBLE);
                customProperties.Put("negative_int", NEGATIVE_INTEGER);
                customProperties.Put("negative_long", NEGATIVE_LONG);
                customProperties.Put("negative_Double", NEGATIVE_DOUBLE);
                customProperties.Put("Boolean", true);
                customProperties.Put("Date", now);
                customProperties.Put("max_int", MAX_INTEGER);
                customProperties.Put("min_int", MIN_INTEGER);
                customProperties.Put("max_long", MAX_LONG);
                customProperties.Put("min_long", MIN_LONG);
                customProperties.Put("max_Double", MAX_DOUBLE);
                customProperties.Put("min_Double", MIN_DOUBLE);
                dsi.CustomProperties = customProperties;

                /* Write the summary information stream and the document summary
                 * information stream to the POI filesystem. */
                si.Write(dir, siEntry.Name);
                dsi.Write(dir, dsiEntry.Name);

                /* Write the POI filesystem to a (temporary) file <em>doc2</em>
                 * and Close the latter. */
                using (FileStream doc2 = File.Create(@".\POI_HPSF_Test2.tmp"))
                {
                    poifs.WriteFileSystem(doc2);
                    //doc2.Flush();

                    /*
                     * Open <em>doc2</em> for Reading and check summary information and
                     * document summary information. All properties written before must be
                     * found in the property streams of <em>doc2</em> and have the correct
                     * values.
                     */
                    doc2.Flush();
                    doc2.Position = 0;
                    POIFSFileSystem poifs2 = new POIFSFileSystem(doc2);
                    dir      = poifs2.Root;
                    siEntry  = (DocumentEntry)dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
                    dsiEntry = (DocumentEntry)dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

                    dis = new DocumentInputStream(siEntry);
                    ps  = new PropertySet(dis);
                    si  = new SummaryInformation(ps);
                    dis = new DocumentInputStream(dsiEntry);
                    ps  = new PropertySet(dis);
                    dsi = new DocumentSummaryInformation(ps);

                    Assert.AreEqual(P_APPLICATION_NAME, si.ApplicationName);
                    Assert.AreEqual(P_AUTHOR, si.Author);
                    Assert.AreEqual(P_CHAR_COUNT, si.CharCount);
                    Assert.AreEqual(P_COMMENTS, si.Comments);
                    Assert.AreEqual(P_CREATE_DATE_TIME, si.CreateDateTime);
                    Assert.AreEqual(P_EDIT_TIME, si.EditTime);
                    Assert.AreEqual(P_KEYWORDS, si.Keywords);
                    Assert.AreEqual(P_LAST_AUTHOR, si.LastAuthor);
                    Assert.AreEqual(P_LAST_PRINTED, si.LastPrinted);
                    Assert.AreEqual(P_LAST_SAVE_DATE_TIME, si.LastSaveDateTime);
                    Assert.AreEqual(P_PAGE_COUNT, si.PageCount);
                    Assert.AreEqual(P_REV_NUMBER, si.RevNumber);
                    Assert.AreEqual(P_SECURITY, si.Security);
                    Assert.AreEqual(P_SUBJECT, si.Subject);
                    Assert.AreEqual(P_TEMPLATE, si.Template);
                    // FIXME (byte array properties not yet implemented): Assert.AreEqual(P_THUMBNAIL, si.Thumbnail);
                    Assert.AreEqual(P_TITLE, si.Title);
                    Assert.AreEqual(P_WORD_COUNT, si.WordCount);

                    Assert.AreEqual(P_BYTE_COUNT, dsi.ByteCount);
                    Assert.AreEqual(P_CATEGORY, dsi.Category);
                    Assert.AreEqual(P_COMPANY, dsi.Company);
                    // FIXME (byte array properties not yet implemented): Assert.AreEqual(P_, dsi.Docparts);
                    // FIXME (byte array properties not yet implemented): Assert.AreEqual(P_, dsi.HeadingPair);
                    Assert.AreEqual(P_HIDDEN_COUNT, dsi.HiddenCount);
                    Assert.AreEqual(P_LINE_COUNT, dsi.LineCount);
                    Assert.AreEqual(P_LINKS_DIRTY, dsi.LinksDirty);
                    Assert.AreEqual(P_MANAGER, dsi.Manager);
                    Assert.AreEqual(P_MM_CLIP_COUNT, dsi.MMClipCount);
                    Assert.AreEqual(P_NOTE_COUNT, dsi.NoteCount);
                    Assert.AreEqual(P_PAR_COUNT, dsi.ParCount);
                    Assert.AreEqual(P_PRESENTATION_FORMAT, dsi.PresentationFormat);
                    Assert.AreEqual(P_SCALE, dsi.Scale);
                    Assert.AreEqual(P_SLIDE_COUNT, dsi.SlideCount);

                    CustomProperties cps = dsi.CustomProperties;
                    //Assert.AreEqual(customProperties, cps);
                    Assert.IsNull(cps["No value available"]);
                    Assert.AreEqual("Wert 1", cps["Schlüssel 1"]);
                    Assert.AreEqual("Wert 2", cps["Schlüssel 2"]);
                    Assert.AreEqual("Wert 3", cps["Schlüssel 3"]);
                    Assert.AreEqual("Wert 4", cps["Schlüssel 4"]);
                    Assert.AreEqual(POSITIVE_INTEGER, cps["positive_int"]);
                    Assert.AreEqual(POSITIVE_LONG, cps["positive_long"]);
                    Assert.AreEqual(POSITIVE_DOUBLE, cps["positive_Double"]);
                    Assert.AreEqual(NEGATIVE_INTEGER, cps["negative_int"]);
                    Assert.AreEqual(NEGATIVE_LONG, cps["negative_long"]);
                    Assert.AreEqual(NEGATIVE_DOUBLE, cps["negative_Double"]);
                    Assert.AreEqual(true, cps["Boolean"]);
                    Assert.AreEqual(now, cps["Date"]);
                    Assert.AreEqual(MAX_INTEGER, cps["max_int"]);
                    Assert.AreEqual(MIN_INTEGER, cps["min_int"]);
                    Assert.AreEqual(MAX_LONG, cps["max_long"]);
                    Assert.AreEqual(MIN_LONG, cps["min_long"]);
                    Assert.AreEqual(MAX_DOUBLE, cps["max_Double"]);
                    Assert.AreEqual(MIN_DOUBLE, cps["min_Double"]);

                    /* Remove all properties supported by HPSF from the summary
                     * information (e.g. author, edit date, application name) and from the
                     * document summary information (e.g. company, manager). */
                    si.RemoveApplicationName();
                    si.RemoveAuthor();
                    si.RemoveCharCount();
                    si.RemoveComments();
                    si.RemoveCreateDateTime();
                    si.RemoveEditTime();
                    si.RemoveKeywords();
                    si.RemoveLastAuthor();
                    si.RemoveLastPrinted();
                    si.RemoveLastSaveDateTime();
                    si.RemovePageCount();
                    si.RemoveRevNumber();
                    si.RemoveSecurity();
                    si.RemoveSubject();
                    si.RemoveTemplate();
                    si.RemoveThumbnail();
                    si.RemoveTitle();
                    si.RemoveWordCount();

                    dsi.RemoveByteCount();
                    dsi.RemoveCategory();
                    dsi.RemoveCompany();
                    dsi.RemoveCustomProperties();
                    dsi.RemoveDocparts();
                    dsi.RemoveHeadingPair();
                    dsi.RemoveHiddenCount();
                    dsi.RemoveLineCount();
                    dsi.RemoveLinksDirty();
                    dsi.RemoveManager();
                    dsi.RemoveMMClipCount();
                    dsi.RemoveNoteCount();
                    dsi.RemoveParCount();
                    dsi.RemovePresentationFormat();
                    dsi.RemoveScale();
                    dsi.RemoveSlideCount();

                    /*
                     * <li>Write the summary information stream and the document summary
                     * information stream to the POI filesystem. */
                    si.Write(dir, siEntry.Name);
                    dsi.Write(dir, dsiEntry.Name);

                    /*
                     * <li>Write the POI filesystem to a (temporary) file <em>doc3</em>
                     * and Close the latter. */
                    using (FileStream doc3 = File.Create(@".\POI_HPSF_Test3.tmp"))
                    {
                        poifs2.WriteFileSystem(doc3);
                        doc3.Position = 0;

                        /*
                         * Open <em>doc3</em> for Reading and check summary information
                         * and document summary information. All properties Removed before must not
                         * be found in the property streams of <em>doc3</em>.
                         */
                        POIFSFileSystem poifs3 = new POIFSFileSystem(doc3);

                        dir      = poifs3.Root;
                        siEntry  = (DocumentEntry)dir.GetEntry(SummaryInformation.DEFAULT_STREAM_NAME);
                        dsiEntry = (DocumentEntry)dir.GetEntry(DocumentSummaryInformation.DEFAULT_STREAM_NAME);

                        dis = new DocumentInputStream(siEntry);
                        ps  = new PropertySet(dis);
                        si  = new SummaryInformation(ps);
                        dis = new DocumentInputStream(dsiEntry);
                        ps  = new PropertySet(dis);
                        dsi = new DocumentSummaryInformation(ps);

                        Assert.AreEqual(null, si.ApplicationName);
                        Assert.AreEqual(null, si.Author);
                        Assert.AreEqual(0, si.CharCount);
                        Assert.IsTrue(si.WasNull);
                        Assert.AreEqual(null, si.Comments);
                        Assert.AreEqual(null, si.CreateDateTime);
                        Assert.AreEqual(0, si.EditTime);
                        Assert.IsTrue(si.WasNull);
                        Assert.AreEqual(null, si.Keywords);
                        Assert.AreEqual(null, si.LastAuthor);
                        Assert.AreEqual(null, si.LastPrinted);
                        Assert.AreEqual(null, si.LastSaveDateTime);
                        Assert.AreEqual(0, si.PageCount);
                        Assert.IsTrue(si.WasNull);
                        Assert.AreEqual(null, si.RevNumber);
                        Assert.AreEqual(0, si.Security);
                        Assert.IsTrue(si.WasNull);
                        Assert.AreEqual(null, si.Subject);
                        Assert.AreEqual(null, si.Template);
                        Assert.AreEqual(null, si.Thumbnail);
                        Assert.AreEqual(null, si.Title);
                        Assert.AreEqual(0, si.WordCount);
                        Assert.IsTrue(si.WasNull);

                        Assert.AreEqual(0, dsi.ByteCount);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(null, dsi.Category);
                        Assert.AreEqual(null, dsi.CustomProperties);
                        // FIXME (byte array properties not yet implemented): Assert.AreEqual(null, dsi.Docparts);
                        // FIXME (byte array properties not yet implemented): Assert.AreEqual(null, dsi.HeadingPair);
                        Assert.AreEqual(0, dsi.HiddenCount);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(0, dsi.LineCount);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(false, dsi.LinksDirty);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(null, dsi.Manager);
                        Assert.AreEqual(0, dsi.MMClipCount);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(0, dsi.NoteCount);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(0, dsi.ParCount);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(null, dsi.PresentationFormat);
                        Assert.AreEqual(false, dsi.Scale);
                        Assert.IsTrue(dsi.WasNull);
                        Assert.AreEqual(0, dsi.SlideCount);
                        Assert.IsTrue(dsi.WasNull);
                    }
                }
            }

            if (File.Exists(@".\POI_HPSF_Test3.tmp"))
            {
                File.Delete(@".\POI_HPSF_Test3.tmp");
            }

            if (File.Exists(@".\POI_HPSF_Test2.tmp"))
            {
                File.Delete(@".\POI_HPSF_Test2.tmp");
            }
        }
Ejemplo n.º 19
0
 public ReaderWriter(POIFSFileSystem fileSystem)
 {
     this.filesystem = fileSystem;
     root            = this.filesystem.Root;
     dataMap         = new Dictionary <object, object>();
 }
Ejemplo n.º 20
0
        public void StandardEncryption()
        {
            FileStream file = POIDataSamples.GetDocumentInstance().GetFile("bug53475-password-is-solrcell.docx");
            String     pass = "******";

            NPOIFSFileSystem nfs = new NPOIFSFileSystem(file);

            // Check the encryption details
            EncryptionInfo infoExpected = new EncryptionInfo(nfs);
            Decryptor      d            = Decryptor.GetInstance(infoExpected);
            bool           passed       = d.VerifyPassword(pass);

            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            // extract the payload
            MemoryStream bos = new MemoryStream();
            Stream       is1 = d.GetDataStream(nfs);

            IOUtils.Copy(is1, bos);
            is1.Close();
            nfs.Close();
            byte[] payloadExpected = bos.ToArray();

            // check that same verifier/salt lead to same hashes
            byte[] verifierSaltExpected = infoExpected.Verifier.Salt;
            byte[] verifierExpected     = d.GetVerifier();
            byte[] keySpec = d.GetSecretKey().GetEncoded();
            byte[] keySalt = infoExpected.Header.KeySalt;


            EncryptionInfo infoActual = new EncryptionInfo(
                EncryptionMode.Standard
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            Encryptor e = Encryptor.GetInstance(infoActual);

            e.ConfirmPassword(pass, keySpec, keySalt, verifierExpected, verifierSaltExpected, null);

            CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifier, infoActual.Verifier.EncryptedVerifier);
            CollectionAssert.AreEqual(infoExpected.Verifier.EncryptedVerifierHash, infoActual.Verifier.EncryptedVerifierHash);

            // now we use a newly generated salt/verifier and check
            // if the file content is still the same

            infoActual = new EncryptionInfo(
                EncryptionMode.Standard
                , infoExpected.Verifier.CipherAlgorithm
                , infoExpected.Verifier.HashAlgorithm
                , infoExpected.Header.KeySize
                , infoExpected.Header.BlockSize
                , infoExpected.Verifier.ChainingMode
                );

            e = Encryptor.GetInstance(infoActual);
            e.ConfirmPassword(pass);

            POIFSFileSystem fs = new POIFSFileSystem();
            Stream          os = e.GetDataStream(fs);

            IOUtils.Copy(new MemoryStream(payloadExpected), os);
            os.Close();

            bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
            fs.WriteFileSystem(bos);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.ToArray());

            // FileOutputStream fos = new FileOutputStream("encrypted.docx");
            // IOUtils.Copy(bis, fos);
            // fos.Close();
            // bis.Reset();

            nfs          = new NPOIFSFileSystem(bis);
            infoExpected = new EncryptionInfo(nfs);
            d            = Decryptor.GetInstance(infoExpected);
            passed       = d.VerifyPassword(pass);
            Assert.IsTrue(passed, "Unable to Process: document is encrypted");

            bos.Seek(0, SeekOrigin.Begin); //bos.Reset();
            is1 = d.GetDataStream(nfs);
            IOUtils.Copy(is1, bos);
            is1.Close();
            nfs.Close();
            byte[] payloadActual = bos.ToArray();

            CollectionAssert.AreEqual(payloadExpected, payloadActual);
            //assertArrayEquals(payloadExpected, payloadActual);
        }
Ejemplo n.º 21
0
        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.ToInputStream(), 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
            {
            }
        }
Ejemplo n.º 22
0
 public ReaderWriter(POIFSFileSystem fileSystem)
 {
     this.filesystem = fileSystem;
     root            = this.filesystem.Root;
     dataMap         = new Hashtable();
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Processes a file into essentially record events.
        /// </summary>
        /// <param name="req">an Instance of HSSFRequest which has your registered listeners</param>
        /// <param name="fs">a POIFS filesystem containing your workbook</param>
        public void ProcessWorkbookEvents(HSSFRequest req, POIFSFileSystem fs)
        {
            Stream in1 = fs.CreateDocumentInputStream("Workbook");

            ProcessEvents(req, in1);
        }
Ejemplo n.º 24
0
 public PropertiesOnlyDocument(POIFSFileSystem fs)
     : base(fs)
 {
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Processes a file into essentially record events.
        /// </summary>
        /// <param name="req">an Instance of HSSFRequest which has your registered listeners</param>
        /// <param name="fs">a POIFS filesystem containing your workbook</param>
        /// <returns>numeric user-specified result code.</returns>
        public short AbortableProcessWorkbookEvents(HSSFRequest req, POIFSFileSystem fs)
        {
            Stream in1 = fs.CreateDocumentInputStream("Workbook");

            return(AbortableProcessEvents(req, in1));
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Creates an HSSFWorkbook from the given POIFSFileSystem
 /// </summary>
 public static IWorkbook Create(POIFSFileSystem fs)
 {
     return(new HSSFWorkbook(fs));
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Writes out the standard Documment Information Properties (HPSF)
 /// </summary>
 /// <param name="outFS">the POIFSFileSystem to Write the properties into</param>
 protected void WriteProperties(POIFSFileSystem outFS)
 {
     WriteProperties(outFS, null);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// This constructor loads a Word document from a POIFSFileSystem
 /// </summary>
 /// <param name="pfilesystem">The POIFSFileSystem that Contains the Word document.</param>
 public HWPFDocumentCore(POIFSFileSystem pfilesystem)
     : this(pfilesystem.Root)
 {
 }
Ejemplo n.º 29
0
 protected void CopyNodes(POIFSFileSystem source, POIFSFileSystem target,
                          List <string> excepts)
 {
     EntryUtils.CopyNodes(source, target, excepts);
 }
Ejemplo n.º 30
0
        public void TestAddToExistingSheet()
        {

            // dvEmpty.xls is a simple one sheet workbook.  With a DataValidations header record but no 
            // DataValidations.  It's important that the example has one SHEETPROTECTION record.
            // Such a workbook can be Created in Excel (2007) by Adding datavalidation for one cell
            // and then deleting the row that Contains the cell.
            IWorkbook wb = HSSFTestDataSamples.OpenSampleWorkbook("dvEmpty.xls");
            int dvRow = 0;
            ISheet sheet = wb.GetSheetAt(0);
            IDataValidationHelper dataValidationHelper = sheet.GetDataValidationHelper();
            IDataValidationConstraint dc = dataValidationHelper.CreateintConstraint(OperatorType.EQUAL, "42", null);
            IDataValidation dv = dataValidationHelper.CreateValidation(dc, new CellRangeAddressList(dvRow, dvRow, 0, 0));

            dv.EmptyCellAllowed = (/*setter*/false);
            dv.ErrorStyle = (/*setter*/ERRORSTYLE.STOP);
            dv.ShowPromptBox = (/*setter*/true);
            dv.CreateErrorBox("Xxx", "Yyy");
            dv.SuppressDropDownArrow = (/*setter*/true);

            sheet.AddValidationData(dv);

            MemoryStream baos = new MemoryStream();
            try
            {
                wb.Write(baos);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }

            byte[] wbData = baos.ToArray();

#if !HIDE_UNREACHABLE_CODE
            if (false)
            { // TODO (Jul 2008) fix EventRecordFactory to process unknown records, (and DV records for that matter)

                ERFListener erfListener = null; // new MyERFListener();
                EventRecordFactory erf = new EventRecordFactory(erfListener, null);
                try
                {
                    POIFSFileSystem fs = new POIFSFileSystem(new MemoryStream(baos.ToArray()));
                    throw new NotImplementedException("The method CreateDocumentInputStream of POIFSFileSystem is not implemented.");
                    //erf.ProcessRecords(fs.CreateDocumentInputStream("Workbook"));
                }
                catch (RecordFormatException e)
                {
                    throw new RuntimeException(e);
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
            }
            // else verify record ordering by navigating the raw bytes
#endif

            byte[] dvHeaderRecStart = { (byte)0xB2, 0x01, 0x12, 0x00, };
            int dvHeaderOffset = FindIndex(wbData, dvHeaderRecStart);
            Assert.IsTrue(dvHeaderOffset > 0);
            int nextRecIndex = dvHeaderOffset + 22;
            int nextSid
                = ((wbData[nextRecIndex + 0] << 0) & 0x00FF)
                + ((wbData[nextRecIndex + 1] << 8) & 0xFF00)
                ;
            // nextSid should be for a DVRecord.  If anything comes between the DV header record 
            // and the DV records, Excel will not be able to open the workbook without error.

            if (nextSid == 0x0867)
            {
                throw new AssertionException("Identified bug 45519");
            }
            Assert.AreEqual(DVRecord.sid, nextSid);
        }
Ejemplo n.º 31
0
 /**
  * Constructs from the default POIFS
  */
 protected POIDocument(POIFSFileSystem fs)
     : this(fs.Root)
 {
 }