I try to use ZipArchive
and ZipArchiveEntry
to create xlsx file, but found it'll lost CompressionOption
and ContentType
and Uri
and Package
information.
normal information like :
but I used below code to and read
create xlsx code:
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;
}
}
read xlsx:
using (Package xlsxPackage = Package.Open(fileName, FileMode.Open, FileAccess.Read))
{
var allParts = xlsxPackage.GetParts();
//...
}
It'll show I lost information
How can I add this information to xlsx? thanks!
Use System.IO.Packaging.ZipPackage
can solve the problem, like below code logic :
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;
}
}