使用 mvc 通过浏览器从数据库导出 excel 文件

Export excel file from database through browser using mvc

我想将 sql table 数据导出到客户端电脑 'through browser' 上的 excel 文件,使用 mvc.Here 我使用的是:

public class ManagementController : Controller
{
  public void ExportitemToExcel()
    {        
        try
        {              
            dt = SqlHelper.LoadTable("SM_GetAllItems", sql);
            if (dt != null && dt.Rows.Count > 0)
            {                   
                ExportToExcel(dt);
            }
        }
        catch
        { throw; }       
    }

这里是导出到excel的方法:

 private void ExportToExcel(DataTable dt)
    {
        Microsoft.Office.Interop.Excel.Application excel;
        Microsoft.Office.Interop.Excel.Workbook worKbooK;
        Microsoft.Office.Interop.Excel.Worksheet worKsheeT;
        excel = new Microsoft.Office.Interop.Excel.Application();
        excel.Visible = false;
        excel.DisplayAlerts = false;
        worKbooK = excel.Workbooks.Add(Type.Missing);

        worKsheeT = (Microsoft.Office.Interop.Excel.Worksheet)worKbooK.ActiveSheet;
        worKsheeT.Name = "Inventory";

        //Create an Excel workbook instance and open it from the predefined location
        // Excel.Workbook excelWorkBook = excel.Workbooks.Open(@"E:\Org.xlsx");
        // Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
        //excelWorkSheet.Name = dt.TableName;

        for (int i = 1; i < dt.Columns.Count + 1; i++)
        {
            worKsheeT.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++)
            {
                worKsheeT.Cells[j + 2, k + 1] = dt.Rows[j].ItemArray[k].ToString();
            }

        }
        string fastExportFilePath = "C:/" + "Inventory" + ".xlsx";

        if (System.IO.File.Exists(fastExportFilePath))
        {
            System.IO.File.Delete(fastExportFilePath);
        }

        worKbooK.SaveAs(fastExportFilePath);
        worKbooK.Close();
        excel.Quit();

这会创建文件,但会以静默方式创建,即不通过浏览器。

您不能将 excel 直接保存到客户端的电脑上。您可以做的是将 excel 保存到服务器并共享给客户端下载。

您可以将 ExportToExcel 方法修改为 return 生成的文件名,您将使用该文件名打开 excel 文件。

private string ExportToExcel(DataTable dt)
{
  //your code goes here
  return fastExportFilePath
}

Javascript

 $(document).ready(function () {
//Check if the hidden field has a value. (Excel was generated)
if ($('#hdnFileName').val() != '')
{
 var url = "Full path to your file" + $('#hdnFileName').val();

                window.location.assign(url)
}
});