下面是我在excel中下载数据的代码,但问题是在下载时没有显示该文件正在下载而且我按照下面给出的方式给出路径下载文件在下载文件夹但是我不应该使用它,因为它在本地主机中工作,但在托管在server.how时它将无法工作。我可以下载到下载文件夹,并在底部显示下载文件
protected void btnExportExcel_Click(object sender, EventArgs e)
{
string pathDownload = @"~\Downloads\" Data.xls";
ExportToExcel(dsExcel, pathDownload);
lblMessage.Text = "Downloaded Successfully";
}
private void ExportToExcel(DataSet table, string filePath)
{
int tablecount = table.Tables.Count;
StreamWriter sw = new StreamWriter(filePath, false);
sw.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
sw.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
sw.Write("<BR><BR><BR>");
sw.Write("<Table border='1' bgColor='#ffffff' borderColor='#000000' cellSpacing='0' cellPadding='0' style='font-size:10.0pt; font-family:Calibri; background:'#1E90FF'> <TR>");
sw.Write("</Table>");
//sw.Write("<BR><BR><BR><BR>");
//sw.Write("\n");
//sw.Write(string.Format("Line1{0}Line2{0}", Environment.NewLine));
sw.Write("</font>");
}
sw.Close();
}
this is the path that i am getting ~\Downloads\DATA.xls
and i am getting this exception Could not find a part of the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\11.0\~\Downloads\DATA.xls'. StreamWriter sw = new StreamWriter(filePath, false);
答案 0 :(得分:0)
目前您的streamwriter写入本地文件。你需要让它写入浏览器。而不是
StreamWriter sw = new StreamWriter(filePath, false);
使用
StreamWriter sw = new StreamWriter(HttpContext.Current.Response.OutputStream);
另外,请务必set the right MIME type并设置content-disposition to trigger a download。
答案 1 :(得分:0)
private void ExportGridToExcel() {
Maingrid.AllowPaging = false;// To print all the pages without pagination in grid
string filename = string.Empty;
filename = "Report -" + DateTime.Now.ToString("yyyyMMddHHmmssfffff");
Response.Clear();
Response.Buffer = true;
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Maingrid.GridLines = GridLines.Both;
Maingrid.HeaderStyle.Font.Bold = true;
int x = Maingrid.Rows.Count;
for (int i = 0; i < Maingrid.Rows.Count; i++)
{
GridViewRow row = Maingrid.Rows[i];
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
row.BackColor = System.Drawing.Color.White;
}
Maingrid.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
//style to format numbers to string
Response.Output.Write("<h1>Merchant Registration report</h1>");
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}