都是些小白菜,昨天问了一个用FileStream导出数据到Excel的,全都说错了。
用FileStream,是没办法下载指定文件的,不管你怎么写,都是浪费力气,最后下载的是整个html页面,包括背景,按钮,查询框,图片,虽然还是xsl格式。而且关闭文档,会弹出是否保存当前修改,如果保存,就会多了一个文件夹,用来装excel里面的其他网页文件,就跟另存为网页是一个样的。
下面这个代码,指定了下载文件,但是下到的是网页:
protected void Button1_Click(object sender, EventArgs e)
{
//打开要下载的文件,并把该文件存放在FileStream中
System.IO.FileStream Reader = System.IO.File.OpenRead(Server.MapPath("~/PeaceScore_End.xls"));
//文件传送的剩余字节数:初始值为文件的总大小
long Length = Reader.Length;
Response.Buffer = false;
//Response.AddHeader("Connection", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + "PeaceScore_End.xls");
Response.AddHeader("Content-Length", Length.ToString());
byte[] Buffer = new Byte[10000];//存放欲发送数据的缓冲区
int ByteToRead;//每次实际读取的字节数
while (Length > 0)
{
//剩余字节数不为零,继续传送
if (Response.IsClientConnected)
{
//客户端浏览器还打开着,继续传送
ByteToRead = Reader.Read(Buffer, 0, 10000);//往缓冲区读入数据
Response.OutputStream.Write(Buffer, 0, ByteToRead);//把缓冲区的数据写入客户端浏览器
Response.Flush();//立即写入客户端
Length -= ByteToRead;//剩余字节数减少
}
else
{
//客户端浏览器已经断开,阻止继续循环
Length = -1;
}
}
Reader.Close();
Response.End();
}
protected void Export_Click1(object sender, EventArgs e)
{
string college = null;
string profession = null;
string subject = null;
string class1 = null;
string semester = null;
if (this.DropDownList_college.SelectedValue != "所有")
{
college += "and College='" + this.DropDownList_college.SelectedValue + "'";
}
else
{
college = null;
}
if (this.DropDownList_profession.SelectedValue != "所有")
{
profession += "and Profession='" + this.DropDownList_profession.SelectedValue + "'";
}
else
{
profession = null;
}
if (this.DropDownList_subject.SelectedValue != "所有")
{
subject += "and Subject='" + this.DropDownList_subject.SelectedValue + "'";
}
else
{
subject = null;
}
if (this.DropDownList_class.SelectedValue != "所有")
{
class1 += "and Class='" + this.DropDownList_class.SelectedValue + "'";
}
else
{
class1 = null;
}
if (this.DropDownList_semester.SelectedValue != "所有")
{
semester += "and Semester='" + this.DropDownList_semester.SelectedValue + "'";
}
else
{
semester = null;
}
sql11 = string.Format("select * from Score where 1=1 {0} {1} {2} {3} {4} order by College,Profession,Class,Subject,Semester", college, profession, subject, class1, semester);
SqlConnection mycon = da.sqlcon;
SqlDataAdapter sqlcmd = new SqlDataAdapter(sql11, mycon);
DataSet ds = new DataSet(); //将查询结果放到DataSet数据集中
sqlcmd.Fill(ds, "Photo"); //这个Photo是ds名称,并不是数据表名,可以随便填,但为了方便,一般都用数据表名。
DataTable DT = ds.Tables[0];
//生成将要存放结果的Excel文件的名称
string NewFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
//转换为物理路径
NewFileName = Server.MapPath("../Temp/" + NewFileName);
//根据模板正式生成该Excel文件
File.Copy(Server.MapPath("../PeaceScore_End.xls"), NewFileName, true);
//建立指向该Excel文件的数据库连接
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + NewFileName + ";Extended Properties='Excel 8.0;'";
OleDbConnection Conn = new OleDbConnection(strConn);
//打开连接,为操作该文件做准备
Conn.Open();
OleDbCommand Cmd = new OleDbCommand("", Conn);
foreach (DataRow DR in DT.Rows)
{
string XSqlString = "insert into [Sheet1$]";
XSqlString += "([登录名],[成绩]) values(";
XSqlString += "'" + DR["StudentName"] + "',";
XSqlString += "'" + DR["Score"] + "')";
Cmd.CommandText = XSqlString;
Cmd.ExecuteNonQuery();
}
Conn.Close();
Response.Redirect("../PeaceScore_End.xls");
}
....这里省略N行
if (File.Exists(Server.MapPath(infor.FileUrl)))
{
try
{
using (FileStream fso = new FileStream(Server.MapPath(infor.FileUrl), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
string filename = infor.FileUrl.Substring(infor.FileUrl.LastIndexOf('.'));
int len = Convert.ToInt32(fso.Length);
byte[] FileObj = new byte[len];
fso.Read(FileObj, 0, len);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", HttpUtility.UrlEncode(infor.title + filename), System.Text.Encoding.UTF8));
Response.AddHeader("Content-Length", len.ToString());
Response.ContentType = "application/octet-stream";
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(FileObj);
fso.Close();
}
}
catch
{
throw (new Exception("文件不存在!"));
}
}
else
{
throw (new Exception("文件不存在!"));
}