ZipArchiveEntry 来创建 xlsx 文件,但发现它会丢失 `CompressionOption` 和 `ContentType` 以及 `Uri` 和 `Package` 信息

ZipArchiveEntry to create xlsx file, but found it'll lost `CompressionOption` and `ContentType` and `Uri` and `Package` information

我尝试使用ZipArchiveZipArchiveEntry创建xlsx文件,但发现它会丢失CompressionOptionContentTypeUriPackage资料。

正常信息如:

但我使用下面的代码阅读

创建 xlsx 代码:

private static FileStream CreateZipFileStream(string path, Dictionary<string, object> filesTree)
{
    using (FileStream stream = new FileStream(path, FileMode.CreateNew))
    {
        using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Create))
        {
            foreach (var fileTree in filesTree)
            {
                ZipArchiveEntry entry = archive.CreateEntry(fileTree.Key);
                using (var zipStream = entry.Open())
                {
                    var bytes = Encoding.ASCII.GetBytes(fileTree.Value.ToString());
                    zipStream.Write(bytes, 0, bytes.Length);
                }
            }
        }
        return stream;
    }
}

阅读 xlsx:

using (Package xlsxPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read))
{
    var allParts = xlsxPackage.GetParts();
    //...
}

它会显示我丢失了信息

如何将此信息添加到 xlsx?谢谢!

使用System.IO.Packaging.ZipPackage可以解决问题,如下代码逻辑:

        private static FileStream CreateZipFileStream(string path, Dictionary<string,ZipPackageInfo> zipPackageInfos)
        {
            using (FileStream stream = new FileStream(path, FileMode.CreateNew))
            using (Package zip = System.IO.Packaging.ZipPackage.Open(stream, FileMode.OpenOrCreate))
            {
                foreach (var p in zipPackageInfos)
                {
                    Uri uri = PackUriHelper.CreatePartUri(new Uri(p.Key, UriKind.Relative));
                    if (zip.PartExists(uri))
                        zip.DeletePart(uri);
                    PackagePart part = zip.CreatePart(uri, p.Value.ContentType,p.Value.CompressionOption);
                    var bytes = Encoding.ASCII.GetBytes(p.Value.Value.ToString());
                    using (Stream dest = part.GetStream())
                        dest.Write(bytes);
                }
                return stream;
            }
        }