C# 中的 Excel 2007 文件编写器导致文件损坏
我使用 BinaryReader 使用 OWA 从 Exchange 邮箱读取 Excel 2007 文件,然后使用 BinaryWriter 将文件写入磁盘。我的问题是当作者完成时这两个文件不匹配。更糟糕的是,Excel 2007 无法打开写入的文件。
以前Excel 2003用下面的解决方案没有问题。如果文件是 Excel 2003 格式的文件,则 Excel 2007 不会出现问题,只有文件格式是 Excel 2007 (*.xlsx) 时才会出现问题。
BinaryReader:
using(System.IO.Stream stream = resource.GetInputStream(attachedFiles[k].Address))
{
using(System.IO.BinaryReader br = new System.IO.BinaryReader(stream))
{
attachment.Data = new byte[attachedFiles[k].Size];
int bufPosn=0, len=0;
while ((len = br.Read( attachment.Data, bufPosn, attachment.Data.Length-bufPosn )) > 0)
{
bufPosn += len;
}
br.Close();
}
}
BinaryWriter:
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter binWriter = new BinaryWriter(fs);
binWriter.Write( content, 0, content.Length );
binWriter.Close();
fs.Close();
感谢收到建议。
I am using a BinaryReader to read an Excel 2007 file from an Exchange mailbox using a OWA, the file is then written to disk using a BinaryWriter. My problem is that the two files don't match when the writer finishes. Worse still Excel 2007 won't open the writen file.
Previously Excel 2003 has had no problem with the solution below. And Excel 2007 doesn't have an issue if the file is an Excel 2003 format file, only if the file format is Excel 2007 (*.xlsx).
BinaryReader:
using(System.IO.Stream stream = resource.GetInputStream(attachedFiles[k].Address))
{
using(System.IO.BinaryReader br = new System.IO.BinaryReader(stream))
{
attachment.Data = new byte[attachedFiles[k].Size];
int bufPosn=0, len=0;
while ((len = br.Read( attachment.Data, bufPosn, attachment.Data.Length-bufPosn )) > 0)
{
bufPosn += len;
}
br.Close();
}
}
BinaryWriter:
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter binWriter = new BinaryWriter(fs);
binWriter.Write( content, 0, content.Length );
binWriter.Close();
fs.Close();
Suggestions gratfully received.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此问题是由 AttachedFiles[k].Size 返回的值远远超过实际文件大小引起的。 Excel 2003 文件似乎不受此影响,但 Excel 2007 文件由于其压缩性质而容易受到攻击(解压缩例程显然会以不同的方式查看该文件)。
一旦我更正了缓冲区的大小,文件就很好了。
感谢您的建议
This issue was caused by the value being returned by attachedFiles[k].Size which was far inexcess of the actual file size. Excel 2003 files it seems are unaffected by this, but Excel 2007 files are vulnerable due to their compressed nature (the decompression routine obviously sees the file differently).
Once I corrected the size of the buffer the files are fine.
Thanks for the suggestions
IE8 和 OWA 存在问题,但我不确定它是否适用于您的情况。
查看此网站,其中还有指向 此网站。他们基本上解释了如何解决使用 OWA 下载 xmlx 和 docx 文件的问题。
There is an issue with IE8 and OWA but I am not sure if it applies in your case.
Checkout this site which also has a link to this site. They basically explain how to get around the problem of download xmlx and docx files with an OWA.