save file as excel is folder using string writer

2.4k views Asked by At

I have created excel file from asp.net table and am now able to download it.

Now I want to save this excel file on the server to be able to use it. I have tried to use string-writer to save the file folder, without succeeding. Here is my code which I have have written to generate file from asp.net.

tbl_loctbl.Controls.Clear();
LoadDetails();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=ProfessorWise.xls");
Response.ContentType = "application/ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
tbl_loctbl.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();

From this code, file is generated and downloaded to user pc.Loaddetails() is function where I load data to asp.net table and then excel file generated. How can I save it to server?

2

There are 2 answers

1
Mana On

If i understood your questing correctly, you want to save files on your webserver with your webapplication.

If you are using IIS on your webserver to run your c# application, then you need to give your folder applicationpool permission where you want to write the excel file/folder to.

the applicationpool must be the same as the webapplication is using.

Update:

First you need to give permission to your folder where you are saving the files/folders. The permission you need to give is the applicationpool your webapplication is using.

After that in IIS you right-click on your site and add a virtual directory. Here you can define the Alias of the folder. Your code will recognize this as an actual folder in project. And you need to chooses the actuall phisical path here.

0
Mahmoude Elghandour On

try to use this

    string path = Server.MapPath("Print_Files"); // folder path
    Random rnd = new Random();
    int month = rnd.Next(1, 13); // creates a number between 1 and 12
    int dice = rnd.Next(1, 7); // creates a number between 1 and 6
    int card = rnd.Next(9); // creates a number between 0 and 51
    string file_name = "filename" +month + dice + card + ".pdf"; // to prevent duplicate 
    FileStream file = new FileStream(path + "/" + file_name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
    file.Write(bytes, 0, bytes.Length);
    file.Dispose();