Skip to main content
 首页 » 编程设计

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

2024年02月05日8shangdawei

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

此处是确定 Excel 文件名称的位置:

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

如您所见,每次我按下 Excel 按钮时,它都会到达其 Controller ,该 Controller 将负责检索数据/保存/创建一个名为 的 .xls 文件事件。

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

Activity_UserName_DateOfCreation 

这是我 Controller 的 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")));