首页 新闻 赞助 找找看

MVC 3中如何实现Excel的下载?使用NPOI

0
悬赏园豆:100 [待解决问题]

MVC3  JQuery 

1、前台

  • <div class="easyui-layout" id="tb">
            <div style="padding: 5px; height: 70px">
                <!-------------------------------搜索框----------------------------------->
                <fieldset>
                    <legend>信息查询</legend>
                    <form id="ffSearch" method="post">
                    <div id="toolbar">
                        <table cellspacing="0" cellpadding="0">
                            <tr>
                                <th>
                                    <label>
                                        年限</label>
                                </th>
                                <td>
                                    <select id="YearSelectedId">
                                        <option value="2005">2005年 </option>
                                        <option value="2006">2006年 </option>
                                        <option value="2007">2007年 </option>
                                        <option value="2008">2008年 </option>
                                        <option value="2009">2009年 </option>
                                        <option value="2010">2010年 </option>
                                        <option value="2011">2011年 </option>
                                        <option value="2012">2012年 </option>
                                        <option value="2013">2013年 </option>
                                        <option value="2014">2014年 </option>
                                        <option value="2015" selected="selected">2015年 </option>
                                    </select>
                                </td>
                                <th>
                                    <label>
                                        行业性质</label>
                                </th>
                                <td>
                                    <select id="HangYeXingZhiId">
                                        <option value="">请选择</option>
                                        <option value="淮安水利">淮安水利</option>
                                        <option value="外埠水利">外埠水利</option>
                                        <option value="电力">电力</option>
                                        <option value="其他">其他</option>
                                    </select>
                                </td>
                                @* <th>
                                    <label>
                                        项目负责人</label>
                                </th>
                                <td>
                                    <select id="Project_FZRId" name="Project_FZR">
                                        <option value="">请选择</option>
                                        <!-----------动态加载人员----------->
                                        @{
                                            List<SKY.SMIS.Model.Sys_UserInfo> userFuzeres = ViewBag.Users;
    
                                            for (int i = 0; i < userFuzeres.Count; i = i + 1)
                                            {
                                                string strName = "ckbs_" + userFuzeres[i].User_ID;                          
                                            <option  value="@userFuzeres[i].User_RealName">@userFuzeres[i].User_RealName
                                            </option>
                                            }
                                                                             
                                        }
                                    </select>
                                </td>*@
                                <td>
                                    <a href="javascript:void(0)" class="easyui-linkbutton" id="btnSearch" onclick="SearchForConditions()">
                                        查询</a>   
                                         <a href="javascript:void(0)" class="easyui-linkbutton"  id="btnExport" iconcls="icon-excel" onclick=" PrintExcel()">导出</a>
                                </td>
                            </tr>
                        </table>
                    </div>
                    </form>
                </fieldset>
            </div>
            <div style="padding: 5px;">
                <table id="tt" style="width: 700px;" title="标题,可以使用代码进行初始化,也可以使用这种属性的方式" iconcls="icon-edit">
                </table>
            </div>
        </div>
    View Code


    2 、传递参数到后台

  • function PrintExcel() {
                var strIds = "";
                if ($("#Project_FZRId").val() != null) {
                    strIds = $("#YearSelectedId").val() + "," + $("#HangYeXingZhiId").val() + "," + $("#Project_FZRId").val() + ",";
                }
                else {
                    strIds = $("#YearSelectedId").val() + "," + $("#HangYeXingZhiId").val() + "," + " " + ",";
                }
                var rows = $("#tt").datagrid('getSelections'); //获取选择的行
                // alert(rows.length);
                if (rows.length <= 0) {
                    $.messager.alert("提示消息", "请选择要导出数据!");
                } else {
                    $.messager.confirm("提示消息", "您确定要导出这些数据吗?", function (r) {
                        if (r) {
                            //通过异步的方式将数据id  发送回后台,然后 后台返回成功过  刷新表格
    
                            for (var i = 0; i < rows.length; i++) { //遍历所有选择的行的json对象集合
                                //alert(rows[i].ID);  1,2,4
                                strIds += rows[i].Project_BiaoHao + ",";
                            }
                            strIds = strIds.substring(0, strIds.length - 1);
    
                            alert(strIds);
    
                            //                        $.ajax({
                            //                            url: "/SunTaskBook/PrintToExcelbyProjectBianhaos", type: "GET",
                            //                            data: {
                            //                                id: strIds
                            //                            },
                            //                            success: function (data) {
                            //                                window.location(data);
                            //                            }
                            //                        });
                            window.location = "/SunTaskBook/PrintToExcelbyProjectBianhaosGenJuMoBan?id=" + strIds;
                        }
                    });
                }
    
            }
    View Code

    3、后台 action

  • public FileContentResult PrintToExcelbyProjectBianhaosGenJuMoBan(string id)
                {
                string[] projectsBianhao = id.Split(',');  //0 1 2 位 传递过来 年限、行业、负责人
                string projecthangyeXingzhi = projectsBianhao[1];
                string projectYear = projectsBianhao[0];
    
                //Excel中从4 开始
                string[] taskNames =
                {
                    "D级GPS", "E级GPS","一级点","二级点","图根点","二等水准","三等水准","四等水准","1:10000", "1:5000", "1:2000地形图", "1:1000地形图", "1:500地形图", "纵断面",
                   "横断面"    , "输变电终勘","输变电定位","输变电终定","初测(km)","定测(km)",    "管线测量","施工放样(点)","建筑物定位(件)",
                   "垂直变形观测","水平变形观测","1:2000外业调绘","1:1000外业调绘","1:500外业调绘","组日"
                };
                FileStream file;
                string filepath = string.Empty;
                string filename = string.Empty;
    
                //  filepath = Server.MapPath("/templete/S测绘项目及主要工作量统计表(2015年1-12月).xls");
                filepath = Server.MapPath("/bin/templete/S测绘项目及主要工作量统计表(2015年1-12月).xls");
                //file = new FileStream(filepath, FileMode.Open, FileAccess.ReadWrite);
    
                //filename = Path.GetFileName(filepath);
    
                file = new FileStream(filepath, FileMode.Open, FileAccess.Read);
    
                NPOI.HSSF.UserModel.HSSFWorkbook book = new HSSFWorkbook();
    
                //读取模板文件,并导入获得的数据表 
                //??为实现该方法
    
                ISheet sheet1 = book.CreateSheet("工作量统计报表");
    
    
                //ProjectSearchParm param = new ProjectSearchParm();
                List<Project_Info> projectsChoosed = new List<Project_Info>();
                for (int i = 3; i < projectsBianhao.Length; i++)
                    {
                    var p = project_InfoService.LoadEntities(p1 => p1.Project_BiaoHao == projectsBianhao[i]).FirstOrDefault();
                    if (p != null)
                        {
                        if (GetProjectHangYe(p.Project_Weituo_Danwei) != projecthangyeXingzhi)
                            {
                            //什么也不错
                            }
                        else
                            {
                            projectsChoosed.Add(p);
                            }
                        }
                    }
                string line = string.Empty;
                if (projectsChoosed.Count > 0)
                    {
    
                    for (int rowNum = 6; rowNum < projectsChoosed.Count + 6; rowNum++)
                        {
                        IRow row = sheet1.CreateRow(rowNum);
                        for (int cellColumNum = 0; cellColumNum < 36; cellColumNum++)
                            {
                            row.CreateCell(cellColumNum);
                            }
                        int count = row.LastCellNum;
    
                        for (int j = 0; j < 36; j++)
                            {
                            if (row.GetCell(j) != null)
                                {
                                row.GetCell(j).SetCellValue("123456");
                                }
                            }
    
                        //row.GetCell(0).SetCellValue(rowNum - 6 + 1);
    
                        //row.GetCell(1).SetCellValue(projectsChoosed[rowNum - 6].Project_BiaoHao);
                        //row.GetCell(2).SetCellValue(projectsChoosed[rowNum - 6].Project_MC);
                        //row.GetCell(3).SetCellValue(projectsChoosed[rowNum - 6].Project_Weituo_Danwei);
    
                        //List<SunTaskBook> tasks = projectsChoosed[rowNum - 6].SunTaskBook.ToList();
    
    
                        /* for (int tasknum = 0; tasknum < tasks.Count; tasknum++)
                         {
                             int index = Array.IndexOf(taskNames, tasks[tasknum].taskbookname);
                             if (index > 0)
                             {
                                 string tempNum, tempmemo;
                                 if (tasks[tasknum].num == null)
                                 {
                                     tempNum = string.Empty;
                                 }
                                 else
                                 {
                                     tempNum = tasks[tasknum].num.ToString();
    
                                 }
                                 if (tasks[tasknum].memo == null)
                                 {
                                     tempmemo = string.Empty;
                                 }
                                 else
                                 {
                                     tempmemo = tasks[tasknum].memo;
    
                                 }
                                 if (row != null && row.GetCell(index + 4) != null)
                                 {
                                     row.GetCell(index + 4).SetCellValue(tempNum + tempmemo);
                                 }
    
                             }
                         }*/
                        }
    
                    }
    
                sheet1.ForceFormulaRecalculation = true;
    
                //传到前台
    
    
                string newfileName = DateTime.Now.ToString("yyyyMMddHHmmssff");
                string downfileName = Server.MapPath(newfileName + ".xls");
    
                filename = projectYear + System.DateTime.Now.ToString() + ".xls";
    
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
                Response.Clear();
    
                using (MemoryStream ms = new MemoryStream())
                    {
                    book.Write(ms);
    
                    // file.Close();
                    Response.BinaryWrite(ms.GetBuffer());
    
    
                 return new FileContentResult(ms.GetBuffer(), "appliaction/vnd.ms-excel");
                  //  return  File(ms.GetBuffer(), "appliaction/vnd.ms-excel");
                   // Response.End();
                    }
    
    
                }
    View Code


    可以实现下载,但是里面的内容是空的?什么原因呀 。求教大神。

shilvyan的主页 shilvyan | 初学一级 | 园豆:104
提问于:2015-05-26 15:03
< >
分享
所有回答(4)
0

1、生成EXCEL和下载是两件事吧?

2、你随便放个EXCEL在指定文件夹,看看下载下来对不对?

3、你得分清楚是生成的问题还是下载的问题。

4、然后你才能成为一个合格的程序员。

爱编程的大叔 | 园豆:30839 (高人七级) | 2015-05-26 15:07

1. 试过了 可以下载下来 但是调试了 中间过程也没问题 单元格也可以取到值;

2、我是想根据前台搜索出来的数据,生成Excel,然后再下载。

3、Excel中Sheet可以生成,只是单元格数据不生成。

支持(0) 反对(0) shilvyan | 园豆:104 (初学一级) | 2015-05-26 15:25

感谢你的回复 。

1. 试过了 可以下载下来 但是调试了 中间过程也没问题 单元格也可以取到值;

2、我是想根据前台搜索出来的数据,生成Excel,然后再下载。

3、Excel中Sheet可以生成,只是单元格数据不生成。

支持(0) 反对(0) shilvyan | 园豆:104 (初学一级) | 2015-05-26 15:26

@shilvyan: 

你知道控制台程序吧?或者Winform?

把你生成EXCEL的代码放到那个里面去单步调试。

支持(0) 反对(0) 爱编程的大叔 | 园豆:30839 (高人七级) | 2015-05-26 15:32

@爱编程的大叔: 好吧,我去试试。

支持(0) 反对(0) shilvyan | 园豆:104 (初学一级) | 2015-05-26 15:34
0

你为什么要加这

Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();
羽商宫 | 园豆:2490 (老鸟四级) | 2015-05-26 16:31

对这块不理解,搜网上的。

支持(0) 反对(0) shilvyan | 园豆:104 (初学一级) | 2015-05-26 17:02

@shilvyan: 去掉response,我一般都是这么写的,你试试

return File(ms.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ceshi.xls");
支持(0) 反对(0) 羽商宫 | 园豆:2490 (老鸟四级) | 2015-05-26 17:09
0

分解为小问题:

1、如何用NPOI生成Excel

2、如何下载文件~

 

BTW:mvc和文件下载没有直接关系。

幻天芒 | 园豆:37175 (高人七级) | 2015-05-27 08:46
0

首先,感谢大家的回复,问题已解决,后台代码没问题,而是前台的问题。

shilvyan | 园豆:104 (初学一级) | 2015-05-29 16:01
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册