KeyValuePair导出到excel

时间:2015-05-24 10:52:57

标签: c# asp.net-mvc entity-framework

我试图将我的数据导出到excel文件,并且我构建对象并将其传递给导出,我想在构建完整对象之前进行检查但是它失败了

public ActionResult ExportToExcel(int roleId, int? levelId)
        {
            var moduleItems = db.C_UserItems
                .Include(x => x.S_Registration)
                .Where(x => x.RoleId == roleId);

            if (levelId != null)
                moduleItems = moduleItems.Where(x => x.S_Registration.LevelId == levelId);

            List<object> objList = new List<object>();
            int i = 0;
            foreach (var item in moduleItems)
            {
                i++;

                List<KeyValuePair<string, object>> obj = new List<KeyValuePair<string, object>>();
                obj.Add(new KeyValuePair<string, object>("Num", i));
                obj.Add(new KeyValuePair<string, object>("Name", item.Name));
                obj.Add(new KeyValuePair<string, object>("Email", item.Email));

                if (roleId == 5)
                {
                    obj.Add(new KeyValuePair<string, object>("Phone", item.Phone));
                    obj.Add(new KeyValuePair<string, object>("CellPhone", item.CellPhone));
                }

                objList.Add(obj);
            }

            SaveToExcel(objList);

            return RedirectToAction("Index", new { id = roleId, levelId = levelId });
        }

这是我的导出方法

protected void SaveToExcel(List<object> objList)
            {
                //Save result as excel file
                HttpResponse response = System.Web.HttpContext.Current.Response;
                // first let's clean up the response.object
                response.Clear();
                // set the response mime type for excel
                response.ContentType = "application/vnd.ms-excel";
                response.AddHeader("Content-Disposition", "attachment;filename=\"Alaglan.xls\"");
                response.ContentEncoding = System.Text.Encoding.Unicode;
                response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

                using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                    {
                        // instantiate a datagrid
                        GridView dg = new GridView();

                        dg.DataSource = objList;
                        dg.DataBind();
                        dg.RenderControl(htw);
                        response.Write(sw.ToString());
                        response.End();
                    }
                }
            }

结果显示为计数,每行的容量,我在构建此对象之前尝试了另一种方式,它运行良好但是很难构建大数据,

if (roleId == 4)
                {
                    objList.Add(new
                    {
                        m = i,
                        name = item.Name,
                        email = item.Email
                    });
                }
                else
                {
                    objList.Add(new
                    {
                        m = i,
                        name = item.Name,
                        email = item.Email,
                        identity = item.S_Registration.Identification
                    });
                }

任何人都可以帮助我,以便通过一些检查来构建对象的最佳方式

1 个答案:

答案 0 :(得分:1)

首先,这对我来说似乎不对:

obj.Add(new KeyValuePair<string, object>("Name", item.Phone));
obj.Add(new KeyValuePair<string, object>("Email", item.CellPhone));

应该是PhoneCellPhone而不是NameEmail

obj.Add(new KeyValuePair<string, object>("Phone", item.Phone));
obj.Add(new KeyValuePair<string, object>("CellPhone", item.CellPhone));

其次,我认为您无法从开箱即用GridView的结构中生成KeyValuePair

但是,我会重写代码以使用DataTable而不是匿名对象和键/值对,并将DataTable绑定到GridView。 它提供了比匿名对象更多的灵活性,并且没有KeyValuePair具有的绑定问题。

例如:

// Create data table to be filled
var DT = new DataTable();
DT.Columns.Add("Num", typeof(int));
DT.Columns.Add("Name");
DT.Columns.Add("Phone");
DT.Columns.Add("CellPhone");

...

int i = 0;
foreach (var item in moduleItems)
{
    i++;

    DataRow Row = DT.NewRow();
    Row["Num"] = i;
    Row["Name"] = item.Name;
    Row["Email"] = item.Email;

    if (roleId == 5)
    {
        Row["Phone"] = item.Phone;
        Row["CellPhone"] = item.CellPhone;
    }

    DT.Rows.Add(Row);
}

...

// instantiate a datagrid
GridView dg = new GridView();

dg.DataSource = DT.DefaultView;
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();