简体   繁体   中英

How to download excel file after exporting data from Dataset to Excel?

Here i dont know how to download Excel File foramt after sending data from Data set to Excel file. this is my code pls help

public void exporttoexcel(DataTable dt)
{   
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;
    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    for (int i = 1; i < dt.Columns.Count + 1; i++)
    {
        xlWorkSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
    }

    for (int j = 0; j < dt.Rows.Count; j++)
    {
        for (int k = 0; k < dt.Columns.Count; k++)
        {
            xlWorkSheet.Cells[j + 2, k + 1] = dt.Rows[j].ItemArray[k].ToString();
        }
    }
    xlWorkBook.Save();
    xlWorkBook.Close();
    xlApp.Quit();
}

I would suggest the following as a guide. Save the excel file to the file system somewhere using the line of code below to specify the location:

xlWorkBook.SaveAs(Path.Combine(filePath, fileName));

Then call the following method passing the file location and name as parameter

private void GenerateFile(string strPath)
{
     var file = new FileInfo(@strPath);

     Response.Clear();
     Response.ContentType = "application/vnd.ms-excel";
     Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
     Response.AddHeader("Content-Length", file.Length.ToString());
     Response.TransmitFile(file.FullName);
     HttpContext.Current.ApplicationInstance.CompleteRequest();
}

This will push the file to be downloaded in the browser if the browser is where you would like to download it from. Alternatively, just save it to the file system as specified using the above line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM