Esempio n. 1
0
        /// <summary>
        /// Main disposal function
        /// </summary>
        protected virtual void Dispose(bool disposing)
        {
            if (Archive == null)
            {
                return;
            }

            if (Archive.Mode != ZipArchiveMode.Read)
            {
                bool ensureSharedStrings = false;

                // Update or create xl/sharedStrings.xml file
                if (SharedStrings != null)
                {
                    ensureSharedStrings = SharedStrings.PendingChanges;
                    SharedStrings.Write();
                }

                // Update xl/_rels/workbook.xml.rels file
                UpdateRelations(ensureSharedStrings);

                // Update xl/workbook.xml file
                string[] sheetNames = UpdateWorkbook();

                // Update [Content_Types].xml file
                UpdateContentTypes(ensureSharedStrings);

                // Update docProps/app.xml file
                UpdateDocPropsApp(sheetNames);
            }

            Archive.Dispose();
        }
Esempio n. 2
0
 public Workbook()
 {
     _sharedStrings = new SharedStrings();
     _cells         = new CellRepo();
     _styles        = new StyleFactory(_cells);
     _sheets        = new WorksheetCollection(_sharedStrings, _cells);
 }
Esempio n. 3
0
 /// <summary>
 /// Reads the XML file form the passed stream and processes the shared strings table
 /// </summary>
 /// <param name="stream">Stream of the XML file</param>
 /// <exception cref="IOException">Throws IOException in case of an error</exception>
 public void Read(MemoryStream stream)
 {
     try
     {
         using (stream) // Close after processing
         {
             XmlDocument xr = new XmlDocument();
             xr.Load(stream);
             StringBuilder sb    = new StringBuilder();
             XmlNodeList   nodes = xr.DocumentElement.ChildNodes;
             foreach (XmlNode node in xr.DocumentElement.ChildNodes)
             {
                 if (node.LocalName.ToLower() == "si")
                 {
                     sb.Clear();
                     GetTextToken(node, ref sb);
                     if (sb.Length > 0)
                     {
                         SharedStrings.Add(sb.ToString());
                     }
                 }
             }
         }
     }
     catch (System.Exception ex)
     {
         throw new IOException("XMLStreamException", "The XML entry could not be read from the input stream. Please see the inner exception:", ex);
     }
 }
Esempio n. 4
0
 /// <summary>
 /// Reads the XML file form the passed stream and processes the shared strings table
 /// </summary>
 /// <param name="stream">Stream of the XML file</param>
 /// <exception cref="Exceptions.IOException">Throws IOException in case of an error</exception>
 public void Read(Stream stream)
 {
     try
     {
         using (stream) // Close after processing
         {
             XmlDocument xr = new XmlDocument();
             xr.XmlResolver = null;
             xr.Load(stream);
             StringBuilder sb = new StringBuilder();
             foreach (XmlNode node in xr.DocumentElement.ChildNodes)
             {
                 if (node.LocalName.Equals("si", StringComparison.InvariantCultureIgnoreCase))
                 {
                     sb.Clear();
                     GetTextToken(node, ref sb);
                     SharedStrings.Add(sb.ToString());
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw new IOException("XMLStreamException", "The XML entry could not be read from the " + nameof(stream) + ". Please see the inner exception:", ex);
     }
 }
Esempio n. 5
0
 public Worksheet(string name, int id, IWorksheetCellCollection cells, SharedStrings strings)
 {
     _strings = strings;
     _cells   = cells;
     Name     = name;
     Id       = id;
     _ns      = new NamespaceDirectory();
 }
        public SheetHDR(ulong Id, string XmlSource, ExcelStream Excel, SharedStrings stringDictionary)
            : base(Id, Excel, stringDictionary)
        {
            var xd = new XmlDocument();
            xd.LoadXml(XmlSource);
            var rows = xd.GetElementsByTagName("row");
            // 遍历row标签
            var flag = false;
            Header = new Header();
            foreach (XmlNode x in rows)
            {
                var cols = x.ChildNodes;
                var objs = new Row(Header);
                // 遍历c标签
                foreach (XmlNode y in cols)
                {
                    string value = null;
                    // 如果是字符串类型,则需要从字典中查询
                    if (y.Attributes["t"]?.Value == "s")
                    {
                        var index = Convert.ToUInt64(y.FirstChild.InnerText);
                        value = StringDictionary[index];
                    }
                    else if (y.Attributes["t"]?.Value == "inlineStr")
                    {
                        value = y.FirstChild.FirstChild.InnerText;
                    }
                    // 否则其中的v标签值即为单元格内容
                    else
                    {
                        value = y.InnerText;
                    }

                    if (!flag)
                    {
                        Header.Add(value, y.Attributes["r"].Value);
                        continue;
                    }
                    objs.Add(value, y.Attributes["r"].Value);
                }
                if (!flag)
                {
                    while (Header.LastOrDefault() == null)
                        Header.RemoveAt(Header.Count - 1);
                    flag = true;
                    continue;
                }
                // 去掉末尾的null
                while (objs.LastOrDefault() == null)
                    objs.RemoveAt(objs.Count - 1);
                if (objs.Count > 0)
                    this.Add(objs);
            }
            while (this.Count > 0 && this.Last().Count == 0)
                this.RemoveAt(this.Count - 1);
            GC.Collect();
        }
Esempio n. 7
0
        // Token: 0x06000CAC RID: 3244 RVA: 0x0006EAE4 File Offset: 0x0006CCE4
        public static TempFileStream CreateInstance(string prefix, bool deleteOnClose)
        {
            NativeMethods.SecurityAttributes securityAttributes = new NativeMethods.SecurityAttributes(false);
            string path = TempFileStream.Path;

            new FileIOPermission(FileIOPermissionAccess.Write, path).Demand();
            int            num  = 0;
            int            num2 = 10;
            string         filename;
            SafeFileHandle safeFileHandle;

            for (;;)
            {
                filename = System.IO.Path.Combine(path, prefix + ((uint)Interlocked.Increment(ref TempFileStream.nextId)).ToString("X5") + ".tmp");
                uint num3 = deleteOnClose ? 67108864U : 0U;
                safeFileHandle = NativeMethods.CreateFile(filename, 1180063U, 0U, ref securityAttributes, 1U, 256U | num3 | 8192U, IntPtr.Zero);
                num2--;
                if (safeFileHandle.IsInvalid)
                {
                    num = Marshal.GetLastWin32Error();
                    if (num == 80)
                    {
                        num2++;
                    }
                    using (Process currentProcess = Process.GetCurrentProcess())
                    {
                        Interlocked.Add(ref TempFileStream.nextId, currentProcess.Id);
                        goto IL_CB;
                    }
                    goto IL_C8;
                }
                goto IL_C8;
IL_CB:
                if (num2 <= 0)
                {
                    break;
                }
                continue;
IL_C8:
                num2 = 0;
                goto IL_CB;
            }
            if (safeFileHandle.IsInvalid)
            {
                string message = SharedStrings.CreateFileFailed(filename);
                throw new IOException(message, new Win32Exception(num, message));
            }
            return(new TempFileStream(safeFileHandle)
            {
                filePath = filename
            });
        }
Esempio n. 8
0
        public void Issue12_AmpersandInCellValues()
        {
            var sharedStrings = new SharedStrings();

            sharedStrings.GetStringIndex("Here & Now");
            sharedStrings.GetStringIndex("&");
            var xmlFile = sharedStrings.ToXmlFile();

            var nodeValues = xmlFile.Content.Descendants(Namespaces.x + "t").Select(x => x.Value).ToList();

            Assert.Contains("Here & Now", nodeValues);
            Assert.Contains("&", nodeValues);
        }
Esempio n. 9
0
        private void ReadContents(string filePath)
        {
            this.filePath = filePath;

            DecompressFolder = Path.GetTempFileName() + @"_excelutility\";
            Directory.CreateDirectory(DecompressFolder);
            new FastZip().ExtractZip(filePath, DecompressFolder, null);

            var contentTypesData = new XElementData(XDocument.Load(string.Format("{0}[Content_Types].xml", DecompressFolder)).Root);

            contentTypes  = new ContentTypes(contentTypesData);
            sharedStrings = new SharedStrings(DecompressFolder + contentTypes.GetSharedStringsPath());
            workbook      = new Workbook(DecompressFolder, contentTypes, sharedStrings);
        }
Esempio n. 10
0
        internal int SetSharedString(string value)
        {
            int stringId;

            if (SharedStringIndex.TryGetValue(value, out stringId))
            {
                return(stringId);
            }

            // Add it
            stringId = SharedStrings.Count;
            SharedStrings.Add(value);
            SharedStringIndex.Add(value, stringId);

            return(stringId);
        }
Esempio n. 11
0
        private void GenerateSharedStringTablePartContent(SharedStringTablePart sharedStringTablePart)
        {
            var sharedStringTable = new SharedStringTable();

            sharedStringTable.Append(SharedStrings.ConvertAll(c => (OpenXmlElement)c));
            List <SharedStringItem> additionalStrings = GetAdditionalSharedStrings();

            if (additionalStrings != null)
            {
                sharedStringTable.Append(additionalStrings.ConvertAll(c => (OpenXmlElement)c));
            }
            if (FileNamesSharedStrings.Any())
            {
                sharedStringTable.Append(FileNamesSharedStrings.ConvertAll(c => (OpenXmlElement)c));
            }

            sharedStringTablePart.SharedStringTable = sharedStringTable;
        }
Esempio n. 12
0
        internal void PrepareArchive(bool openSharedStrings = true)
        {
            if (Archive == null)
            {
                if (ReadOnly)
                {
                    Archive = ZipFile.Open(ExcelFile.FullName, ZipArchiveMode.Read);
                }
                else
                {
                    Archive = ZipFile.Open(ExcelFile.FullName, ZipArchiveMode.Update);
                }
            }

            // Get Strings file
            if (SharedStrings == null && openSharedStrings)
            {
                SharedStrings = new SharedStrings(Archive);
            }
        }
Esempio n. 13
0
    public const int SettingSize = 6; // 2 bytes for the id, 4 bytes for the value.

    public static bool TryReadFrame(ref ReadOnlySequence <byte> buffer, Http2Frame frame, uint maxFrameSize, out ReadOnlySequence <byte> framePayload)
    {
        framePayload = ReadOnlySequence <byte> .Empty;

        if (buffer.Length < HeaderLength)
        {
            return(false);
        }

        var headerSlice = buffer.Slice(0, HeaderLength);
        var header      = headerSlice.ToSpan();

        var payloadLength = (int)Bitshifter.ReadUInt24BigEndian(header);

        if (payloadLength > maxFrameSize)
        {
            throw new Http2ConnectionErrorException(SharedStrings.FormatHttp2ErrorFrameOverLimit(payloadLength, maxFrameSize), Http2ErrorCode.FRAME_SIZE_ERROR);
        }

        // Make sure the whole frame is buffered
        var frameLength = HeaderLength + payloadLength;

        if (buffer.Length < frameLength)
        {
            return(false);
        }

        frame.PayloadLength = payloadLength;
        frame.Type          = (Http2FrameType)header[TypeOffset];
        frame.Flags         = header[FlagsOffset];
        frame.StreamId      = (int)Bitshifter.ReadUInt31BigEndian(header.Slice(StreamIdOffset));

        var extendedHeaderLength = ReadExtendedFields(frame, buffer);

        // The remaining payload minus the extra fields
        framePayload = buffer.Slice(HeaderLength + extendedHeaderLength, payloadLength - extendedHeaderLength);
        buffer       = buffer.Slice(framePayload.End);

        return(true);
    }
        public void Read(Stream stream)
        {
            SharedStrings.Clear();
            XmlTextReader xr = new XmlTextReader(stream);
            bool          isStringItem = false, isText = false;
            string        item = "";
            string        name;

            while (xr.Read())
            {
                name = xr.Name.ToLower();
                if (name == "si" && xr.IsStartElement() == true)
                {
                    isStringItem = true;
                    continue;
                }
                else if (name == "t" && isStringItem == true)
                {
                    isText = true;
                    continue;
                }
                else if (string.IsNullOrEmpty(name) && isText)
                {
                    item = xr.ReadString();
                    continue;
                }
                else if (name == "si" && isStringItem == true && isText == true)
                {
                    SharedStrings.Add(item);
                    item         = "";
                    isText       = false;
                    isStringItem = false;
                    continue;
                }
            }
        }
Esempio n. 15
0
 public TextCell(SharedStrings strings, CellAddress address, string value) : base(address)
 {
     _value = strings.AddString(value);
 }
Esempio n. 16
0
 public void Dispose()
 {
     ZipArchive?.Dispose();
     FileStream?.Dispose();
     SharedStrings?.Dispose();
 }