更改Excel行

时间:2015-10-29 08:32:01

标签: c# asp.net-mvc excel

我有一个控制器,可以获取我页面上显示的数据并使用它创建一个Excel电子表格。

以下是Excel控制器没有检索数据(因为它与我的问题无关):

[Authorize]
public ActionResult Excel(string user)
{
    var products = new System.Data.DataTable("Activity");                        

    products.Columns.Add("Project", typeof(string));

    int counter = 0;
    foreach (var jour in ListDaysOfMonth)
    {
        products.Columns.Add(jour, typeof(int));
        counter++;
    }

    List<string[]> lstInts = new List<string[]>();

    foreach (Project p in lp)
    {             
           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);             
    }

    int i = 0;
    int y = 1;
    int z = 0;
    foreach (string[] tab in lstInts)
    {
        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", string.Format("attachment; filename=Activity_{0}.xls", DateTime.Now.Date.ToString("yyyyMMdd")));
    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");
}      

以下是通过此过程创建的Excel电子表格示例:

enter image description here

但这是我的问题:

由于我使用products.Columns.Add添加列,因此无法找到在网格中进一步创建所述列的方法,以便我可以在其左上角添加新信息。

每个例子,让当前现有的列从单元格E9开始,这样我就可以在电子表格的左上角找到创建日期和员工等信息。

为了做到这一点我应该改变什么?

这是所需输出的样子:

enter image description here

1 个答案:

答案 0 :(得分:0)

不确定是否最好,但您可以尝试

        var employee = "Employee Name";
        var month = "October";
        var year = "2015";

        htw.WriteLine("Year: {0}<br/>Month: {1}<br>Employee: {2}<br/>",year,month,employee);
        grid.RenderControl(htw);