使用MVC3在Excel中下载数据

时间:2013-07-23 12:47:11

标签: c# asp.net-mvc asp.net-mvc-3 download

我正在使用Asp Dot Net Mvc3我想下载Excel文件。以下是我的控制器,

public ActionResult DownloadTRUnutilizedOwnershipInvoke(string strGeo, string strVertical, int intMonth, int intFlag,string strType)
{
     TRUnutilizedOwnershipModel objTRUnutilizedOwnershipModel = new TRUnutilizedOwnershipModel();
     objTRUnutilizedOwnershipModel = objTRUnutilizedOwnershipModel.GetUnutilizedOwnershipExcelEntities(strGeo, strVertical, intMonth, intFlag,strType);
     objTRUnutilizedOwnershipModel.ExportUnutilizedOwnership("UnutilizedOwnership", objTRUnutilizedOwnershipModel.lstunutilizedownershipExcelentities);                                           
}

以下是我的模特,

       public void ExportUnutilizedOwnership<T>(string fileName, List<T> lstdata)
    {
        try
        {
            Table tableData = new Table();                                               HttpContext.Current.Response.Clear();                
      HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName + ".xls"));.
            HttpContext.Current.Response.ContentType = "application/ms-excel";= "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";                using (StringWriter sw = new StringWriter())
            {
                                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    if (typeof(T) == typeof(UnutilizedOwnershipExcelEntities))
                    {
                        List<UnutilizedOwnershipExcelEntities> lstNewdata = (List<UnutilizedOwnershipExcelEntities>)(object)lstdata;
                        tableData = TableUnutilizedOwnershipExcelData(lstNewdata);
                    }                                                                                            tableData.RenderControl(htw);                                       HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

          public Table TableUnutilizedOwnershipExcelData(List<UnutilizedOwnershipExcelEntities> lstUnutilizedOwnershipExcelEntities)
    {
        try
        {
            Table tableData = new Table();
            TableRow rowHeader = new TableRow();
            TableHeaderCell hCurrentOwnership = new TableHeaderCell();
            TableHeaderCell hCount = new TableHeaderCell();

            hCurrentOwnership.Text = "CurrentOwnership";
            hCount.Text = "Count";

            rowHeader.Cells.Add(hCurrentOwnership);
            rowHeader.Cells.Add(hCount);

            rowHeader.BackColor = Color.Gray;
            ApplyStyle(rowHeader);
            tableData.Rows.Add(rowHeader);
            foreach (UnutilizedOwnershipExcelEntities excelEntity in lstUnutilizedOwnershipExcelEntities)
            {
                TableRow rowData = new TableRow();

                TableCell cellCurrentOwnership = new TableCell();
                TableCell cellCount = new TableCell();

                cellCurrentOwnership.Text = excelEntity.CurrentOwnership;
                cellCount.Text = Convert.ToString(excelEntity.cnt);

                rowData.Cells.Add(cellCurrentOwnership);
                rowData.Cells.Add(cellCount);

                tableData.Rows.Add(rowData);
                ApplyStyle(rowData);
            }
            return tableData;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    public void ApplyStyle(TableRow row)
    {
        try
        {
            row.BorderColor = Color.FromName("#CCCCCC");
            row.BorderWidth = Unit.Pixel(1);
            row.BorderStyle = BorderStyle.Solid;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

我无法获取下载Excel的弹出窗口。我是否错过了此代码中的任何内容以获取下载Excel弹出窗口的弹出窗口

1 个答案:

答案 0 :(得分:0)

试试这个,

 [HttpPost]
            public ActionResult ActionMethods(ActionModel model)
            {
                if (model != null)
                {
                    string contentType = "application/xlx";
                    string fileExtension = ".xlsx";


                    DataTable dt = //Set your data which is reflect on excel

                    ExcelExport.SaveToExcelFile(dt, strFilePath);

                  return File(strFilePath, contentType, "Reports" + fileExtension);
                        }
                    }
                }
                return RedirectToAction("Action");
            }

   public static void SaveToExcelFile(System.Data.DataTable dt, string filename)
        {
            Application app = new Application();
            try
            {
                Workbook wb = app.Workbooks.Add(1);
                Worksheet ws = (Worksheet)wb.Worksheets[1];


                Style ColumnStyle = wb.Styles.Add("Style1", Type.Missing);
                ColumnStyle.Font.Bold = true;
                ColumnStyle.Interior.Color = System.Drawing.Color.Yellow;


                // export column headers
                for (int colNdx = 0; colNdx < dt.Columns.Count; colNdx++)
                {
                    ws.Cells[1, colNdx + 1] = dt.Columns[colNdx].ColumnName;
                    Range exrange = (ws.Cells[1, colNdx + 1]) as Range;
                    exrange.Style = ColumnStyle;
                }

                // export data
                for (int rowNdx = 0; rowNdx < dt.Rows.Count; rowNdx++)
                {
                    for (int colNdx = 0; colNdx < dt.Columns.Count; colNdx++)
                    {
                        ws.Cells[rowNdx + 2, colNdx + 1] = dt.Rows[rowNdx][colNdx];
                    }
                }
                wb.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
                    Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing);
                wb.Close(false, Type.Missing, Type.Missing);
            }
            finally
            {
                app.Quit();
            }

        }