开发者

How to export an Excel from dataset and save it into a specific path without showing the save as box

I have a code to exporting dataset to excel working fine, I want to expo开发者_开发问答rting the excel into a specific location on the server, my code is down here and what changes should I do: Any ideas?

public static void ExportDataSetToExcel(DataSet ds, string filename, string path)
{
   HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.Charset = "";
    response.ContentType = "application/vnd.ms-excel";
    response.AddHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter htw = new HtmlTextWriter(sw))
        {
            // instantiate a datagrid
            DataGrid dg = new DataGrid();
            dg.DataSource = ds.Tables[0];
            dg.DataBind();
            dg.RenderControl(htw);
            response.Write(sw.ToString());
            response.End();
        }
    }
}


I don't believe it is possible to download the way you are describing. That would be a large security risk if browsers allowed this.


This isn't possible. The browser can't directly access the user's file system because of the obvious security risks that would entail. If you are providing a file download service from your website, you have to accept that the user will be prompted with the 'Save File' dialog by the browser.


If you just want to save to a file, you only need to use the StringWriter class. You need to add the path for the file to be saved into the constructor for the StringWriter, as so (assuming the path does not include the filename. And you need to close the StringWriter:

using (StringWriter sw = new StringWriter(path + filename))
{
    // use 'sw.Write(text)' to write to the file
    sw.Close();
}

EDIT: If you want to push the Excel file to a server, you need to use some other method. You can't push HTTP requests like that.


I made it working, by using FileStream fs = new FileStream(Server.MapPath("ExcelFile\File1.xls"), FileMode.Create); try { Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes(htmlmarkup); fs.Write(bContent, 0, bContent.Length); } it can create the file into server and use the code on my post can use the xls on your local disk. I conbined the two method it works fine for me

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜