我有一个Web表单页面,应该能够将Crystal Report的内容写入pdf或excel文档,具体取决于用户的选择。
我有两个问题:
对于.pdf和.xls扩展名,都有一个括号 在它内部附加到扩展IE:fileName.xls'1'
如果用户选择excel文档,则在IE中显示文件下载提示 出现并询问我们是否要保存或打开文件:
PDF文件保存得很好,但是如果我们选择打开excel文件,它会打开一个资源管理器窗口,我们会得到垃圾......
这是我们的代码:
try
{
permission = new FileIOPermission(FileIOPermissionAccess.Read, output);
fs = File.Open(output, FileMode.Open, FileAccess.Read);
byte[] byteArray = new byte[fs.Length];
fs.Read(byteArray, 0, (int)fs.Length);
fs.Close();
fs.Dispose();
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
fileName = fileName + '.' + extn;
//Response.AddHeader("Content-Disposition", "attachments;filename=\"" + fileName + ".\"" + extn);
Response.AddHeader("Content-Disposition", "attachments;filename=\"" + fileName + "\"");
Response.AddHeader("Content-Length", byteArray.Length.ToString());
switch ("." + extn)
{
case ".pdf":
Response.AppendHeader("Content-Type", "application/pdf");
break;
case ".xls":
//Response.ContentType = "application/vnd.ms-excel";
//Response.ContentType = "application/octet-stream";
Response.AppendHeader(".xls", "application/excel");
//Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
//Response.AppendHeader("Content-Type", "application/force-download");
break;
case ".txt":
Response.AppendHeader("Content-Type", "application/notepad");
break;
}
FileInfo info = new FileInfo(output);
info.Delete();
Response.BinaryWrite(byteArray);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
if (fs != null)
fs.Close();
}
我一直在研究人们遇到“1”附加到扩展名的现象,但是在其上找不到很多,并调试了代码并确认扩展名是干净的。< / p>
我的下一个猜测是在Response.BinaryWrite(byteArray)中发生的事情;行或mime类型或内容标题...
提前感谢您的任何帮助
道格
答案 0 :(得分:0)
我在项目中做了类似的事情。 我已粘贴下面的代码。 我想,你突然更换了这条线。 Response.AppendHeader(“。xls”,“application / excel”); 同 Response.ContentType =“application / excel”;
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".docx":
case ".rtf":
type = "Application/msword";
break;
case ".pdf":
type = "application/pdf";
break;
case ".csv":
case ".xlsx":
type = "application/vnd.ms-excel";
break;
}
}
Response.AppendHeader("content-disposition",
"attachment; filename=" + name);
if (string.IsNullOrEmpty(type))
{
}
else
{
Response.ContentType = type;
}
Response.WriteFile(path);
Response.End();
答案 1 :(得分:0)
将switch
扩展为以下内容:
switch ("." + extn)
{
// case ".pdf":
// ...
default:
throw new NotImplementedException();
}
如果抛出异常,这可能会给你一个关于出错的提示。