public void TestDetectAsPOIFS() { Stream in1; // ooxml file is in1 = new PushbackStream( HSSFTestDataSamples.OpenSampleFileStream("SampleSS.xlsx") ); Assert.IsTrue(POIXMLDocument.HasOOXMLHeader(in1)); in1.Close(); // xls file isn't in1 = new PushbackStream( HSSFTestDataSamples.OpenSampleFileStream("SampleSS.xls") ); Assert.IsFalse(POIXMLDocument.HasOOXMLHeader(in1)); in1.Close(); // text file isn't in1 = new PushbackStream( HSSFTestDataSamples.OpenSampleFileStream("SampleSS.txt") ); Assert.IsFalse(POIXMLDocument.HasOOXMLHeader(in1)); in1.Close(); }
/** * Takens an InputStream, verifies that it's not RTF, builds a * POIFSFileSystem from it, and returns that. */ public static POIFSFileSystem VerifyAndBuildPOIFS(Stream istream) { // Open a PushbackInputStream, so we can peek at the first few bytes PushbackStream pis = new PushbackStream(istream); byte[] first6 = new byte[6]; pis.Read(first6, 0, 6); // Does it start with {\rtf ? If so, it's really RTF if (first6[0] == '{' && first6[1] == '\\' && first6[2] == 'r' && first6[3] == 't' && first6[4] == 'f') { throw new ArgumentException("The document is really a RTF file"); } // OK, so it's not RTF // Open a POIFSFileSystem on the (pushed back) stream pis.Unread(6); return new POIFSFileSystem(istream); }
/// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given InputStream. The Stream is wraped inside a PushbackInputStream. /// </summary> /// <param name="inputStream">Input Stream of .xls or .xlsx file</param> /// <returns>IWorkbook depending on the input HSSFWorkbook or XSSFWorkbook is returned.</returns> // Your input stream MUST either support mark/reset, or // be wrapped as a {@link PushbackInputStream}! public static IWorkbook Create(Stream inputStream) { // If Clearly doesn't do mark/reset, wrap up //if (!inp.MarkSupported()) //{ // inp = new PushbackInputStream(inp, 8); //} inputStream = new PushbackStream(inputStream); if (POIFSFileSystem.HasPOIFSHeader(inputStream)) { return new HSSFWorkbook(inputStream); } inputStream.Position = 0; if (POIXMLDocument.HasOOXMLHeader(inputStream)) { return new XSSFWorkbook(OPCPackage.Open(inputStream)); } throw new ArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream."); }