将一个{0}variables添加到Excel电子表格名称

我正在创buildExcel电子表格,显示当前在我的网页上为我的内联网显示的数据。 它工作顺利,但我希望有不同的文件名称(取决于用户login,创build时间等)。

这是确定Excel文件名称的地方:

Response.AddHeader("content-disposition", "attachment; filename=Activity.xls"); 

正如你所看到的,每次我按Excelbutton,它都会到达它的控制器,它将负责检索数据/保存/创build一个名为Activity.xls文件。

我是新手,听说使用{0}向C#中的string添加参数。 会有类似的东西,所以我可以这样命名我的文件:

 Activity_UserName_DateOfCreation 

这里是我的控制器的Excel部分,而不是数据收集:

 [Authorize] public ActionResult Excel(string user) { var products = new System.Data.DataTable("Activity"); // Creates the DataTable products.Columns.Add("Project", typeof(string)); // Adds a column IEnumerable<Project> lp = _service.List(strUser, strYear, strMonth); // Creates a list of the projects UserActivityDb db = new UserActivityDb(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString); lp = lp.Where(p => (true == db.ExistUserActivity(int.Parse(strYear), int.Parse(strMonth), ListDaysOfMonth, p.ProjectId, strUser))); List<string[]> lstInts = new List<string[]>(); foreach (Project p in lp) { string strInts = db.getFormattedData(int.Parse(strYear), int.Parse(strMonth), ListDaysOfMonth, p.ProjectId, strUser, null, 0); string[] ints = strInts.Split(';'); lstInts.Add(ints); products.Rows.Add(p.Name, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); // Adds an empty row to be filed with the correct values later } int i = 0; int y = 1; int z = 0; foreach (string[] tab in lstInts) // Adds the activity data cell by cell { while (tab[z] != "") { products.Rows[i][y] = tab[z]; y++; z++; } i++; y = 1; z = 0; } var grid = new GridView(); grid.DataSource = products; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=Activity.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); return View("Excel"); } 

当然,你可以做这样的事情:

 Response.AddHeader("content-disposition", string.Format("attachment; filename=Activity_{0}_{1}.xls",strUser, DateTime.Now.Date.ToString("MMddyyyy"))); 

只要在这里添加一个DrewJordans方法的替代scheme,即使这个方法没有任何问题。 就像这种方法更好,为了可读性:

 Response.AddHeader("content-disposition", $"attachment; filename=Activity_{strUser}_{DateTime.Now.Date.ToString("MMddyyyy")}.xls"); 

只要join这个,如果你想阅读更多关于内插string。