0

I am exporting excel file from database using following method.But i have one problem when i am exporting excel file than it is automatically downloading to download folder and i don't want this to be happen,I want my excel file to be downloaded in my project folder

var formsection = from fs in db.FormSections
                  join form in Form on fs.FormId equals form.FormId
                  select fs;
XLWorkbook wb = new XLWorkbook();              
string sheetName = "ARTICLE"; //Give name for export file.               

var Fs = wb.Worksheets.Add("FORMSECTION");
Fs.Cell(2, 1).InsertTable(formsection.ToList());// assign list here.
HttpContext.Response.Clear();
HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx", sheetName.Replace(" ", "_")));
var filePath = Path.Combine(Server.MapPath("~/Content"));
using (MemoryStream memoryStream = new MemoryStream())
{                  
    wb.SaveAs(memoryStream);                     
    memoryStream.WriteTo(HttpContext.Response.OutputStream);
    memoryStream.Close();
}               
HttpContext.Response.End();
2
  • 3
    You cannot control where it is downloaded on the client-side. Commented Oct 11, 2014 at 8:07
  • @JeremyThompson i just want to encrypt the file before download how to do that Commented Oct 11, 2014 at 8:09

3 Answers 3

3

Here is an example that converts a datatable to a .csv file and save the file to the folder of your project for me its store the file in Domestic folder as the path given by me.

private void test(DataTable dt1) {

    string csv = string.Empty;

    foreach (DataColumn column in dt1.Columns)
    {
        //Add the Header row for CSV file.
        csv += column.ColumnName + ',';
    }

    //Add new line.
    csv += "\r\n";

    foreach (DataRow row in dt1.Rows)
    {
        foreach (DataColumn column in dt1.Columns)
        {
            //Add the Data rows.
            csv += row[column.ColumnName].ToString().Replace(",", ";") +',';
        }

        //Add new line.
        csv += "\r\n";
    }

    string datetime = Convert.ToString(DateTime.Today.ToString("dd-MM-yyyy")).Trim();
    string filepath = "C:\\Users\\Prateek\\Desktop\\MMR New  27-07 -\\Domestic\\";
    string filename= @"BILLING_BOOK_NO" + "_4005" + "_"+datetime+".CSV";
    string combinepath = filepath + filename;          
   System.IO.File.WriteAllText(combinepath,csv);
}`
Sign up to request clarification or add additional context in comments.

Comments

1

You need to write the excel to your server first.

wb.SaveAs(filePath);
//encrypt the file
Encrypt(filePath);
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        byte[] bytes = new byte[file.Length];
        file.Read(bytes, 0, (int)file.Length);
        memoryStream.Write(bytes, 0, (int)file.Length);
        memoryStream.WriteTo(HttpContext.Response.OutputStream);
    }
}

5 Comments

Access to the path 'C:\Users\Neeraj\Documents\Visual Studio 2013\Projects\Planetskool\Planetskool\Planetskool\Content' is denied ..Getting error in wb.SaveAs(filepath);
Try this: var filePath = Path.Combine(Server.MapPath("~/Content"), string.Format("{0}.xls", Guid.NewGuid().ToString())
use this filepath file is downloaded to download folder of chrome :(
ya it is done but is is downloading two file one to downloads and one to content
So, you need to delete the file in content folder after response. This file is used for encryption.
0

use code as below

    public void ImportXLX()
        {

string filePath = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), @"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx");
                    if (System.IO.File.Exists(filePath))
                        System.IO.File.Delete(filePath);
                    Request.Files["xlsFile"].SaveAs(filePath);
                    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.