gpt4 book ai didi

c# - 打开使用 EPPlus 创建并使用 ICSharpCode.SharpZipLib 压缩到文件夹中的 .xlsx 文件时出现问题

转载 作者:行者123 更新时间:2023-11-30 16:12:07 29 4
gpt4 key购买 nike

我正在使用 EPPlus 创建 ExcelPackages(xlsx 文档)列表,并将它们作为 ZipEntries 添加到 ZipOutputStream。我认为 Excel 文档应该是有效的,因为当我将其中一个文档写入 Response 对象而不压缩时,我可以很好地打开它们。
zip 文件夹按预期创建,文件在那里并且似乎不是空的,但是当我尝试打开它们时,我在 Excel 中收到以下错误:

Excel cannot open the file {Name}.xlsx because the file format or file extension is not valid. Verify that file has not been corrupted and that the file extension matches the format of the file

List<ExcelPackage> documents = new List<ExcelPackage>();
List<string> fileNames = new List<string>();

//Code for fetching documents and filenames here (removed for the sake of readability)

Response.Clear();
Context.Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=\"random-foldername.zip\"");
Response.CacheControl = "Private";
Response.Cache.SetExpires(DateTime.Now.AddMinutes(3));

ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream);
zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression
byte[] buffer = null;

for (int i = 0; i < documents.Count; i++)
{
MemoryStream ms = new MemoryStream();

documents[i].SaveAs(ms);

ZipEntry entry = new ZipEntry(ZipEntry.CleanName(fileNames[i]));

zipOutputStream.PutNextEntry(entry);
buffer = new byte[ms.Length];

ms.Read(buffer, 0, buffer.Length);
entry.Size = ms.Length;

ms.Close();

zipOutputStream.Write(buffer, 0, buffer.Length);
zipOutputStream.CloseEntry();

}
zipOutputStream.Finish();
zipOutputStream.Close();

Response.End();

至于文件名列表,我只是根据一些任意的东西生成一个名称并在其末尾添加一个“.xlsx”扩展名。

我不确定我哪里出了问题,有什么建议吗?

最佳答案

你必须倒回内存流才能读取内容(在写操作文件指针结束后):

ms.Seek(0, SeekOrigin.Begin)
ms.Read(buffer, 0, buffer.Length);

也就是说 MemoryStream 只不过是一个字节数组,所以您甚至不需要分配和读取一个新的,然后这段代码:

buffer = new byte[ms.Length];

ms.Read(buffer, 0, buffer.Length);
entry.Size = ms.Length;

ms.Close();

zipOutputStream.Write(buffer, 0, buffer.Length);

可以简单地替换为:

entry.Size = ms.Length;
zipOutputStream.Write(ms.GetBuffer(), 0, ms.Length);
ms.Close();

最后的说明:如果你不想使用内部 MemoryStream 缓冲区(出于任何原因)并且你想要它的修剪副本(就像你手动做的那样)那么只需使用 ToArray() 方法如下:

var buffer = ms.ToArray();
ms.Close();
entry.Size = buffer.Length;
zipOutputStream.Write(buffer, 0, buffer.Length);

关于c# - 打开使用 EPPlus 创建并使用 ICSharpCode.SharpZipLib 压缩到文件夹中的 .xlsx 文件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23472385/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com