将{0}变量添加到Excel电子表格名称中

本文关键字:电子表格 Excel 添加 变量 | 更新日期: 2023-09-27 18:19:48

我正在创建Excel电子表格,显示当前显示在我的intranet页面上的数据。它运行得很顺利,但我希望有不同的文件名(取决于用户登录、创建时间等)

这里是Excel文件名称的确定位置:

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

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

我是这项技术的新手,听说过使用{0}在C#中为字符串添加参数是否有类似的东西,以便我可以这样命名我的文件:

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");
}

将{0}变量添加到Excel电子表格名称中

当然,你可以这样做:

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

只是在这里添加一个DrewJordans方法的替代方案,尽管它可以在没有任何问题的情况下工作。就像这种方法更好,为了可读性:

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

如果你想了解更多关于插值字符串的信息,只需添加这个即可。