示例#1
0
        public ActionResult ExportExcel(string gridUrl,
                                        string referUrl,
                                        string pageNumber,
                                        string pageSize,
                                        string queryParams,
                                        string title,
                                        string sortName,
                                        string sortOrder,
                                        string columns)
        {
            var postData = new Dictionary <string, object>();

            if (!string.IsNullOrEmpty(queryParams))
            {
                postData = queryParams.JsonToDictionary();
            }

            var serverUrl  = string.Format("{0}://{1}", Request.Url.Scheme, Request.Headers["Host"]);
            var requestUrl = gridUrl;

            var dicList = GetDicList(serverUrl, requestUrl, referUrl, postData);

            DataTable dt = null;

            if (!string.IsNullOrEmpty(columns))
            {
                dt = new DataTable();
                var columnDic = columns.JsonToDictionaryList();
                foreach (var dic in columnDic)
                {
                    if (!dt.Columns.Contains(dic.GetValue("title")))
                    {
                        dt.Columns.Add(dic.GetValue("title"));
                    }
                }

                foreach (var dic in dicList)
                {
                    DataRow dr = dt.NewRow();
                    foreach (var item in dic)
                    {
                        var column = columnDic.FirstOrDefault(a => a.GetValue("field") == item.Key);
                        if (column != null)
                        {
                            dr[column.GetValue("title")] = item.Value;
                        }
                    }
                    dt.Rows.Add(dr);
                }
            }
            else
            {
                dt = DictionaryExtend.ConvertDicToTable(dicList.ToList());
            }

            var buffer = NPOIExcelHelper.Export(dt, "").GetBuffer();

            buffer.CheckNotNull("导出excel出现异常");
            return(File(buffer, "application/vnd.ms-excel", Url.Encode(title) + ".xls"));
        }
 /// <summary>
 /// 导出数据
 /// </summary>
 protected virtual void ExportData()
 {
     try
     {
         if (GridView == null)
         {
             return;
         }
         SaveFileDialog dig = new SaveFileDialog();
         dig.Filter           = "Excel文档|*.xls;*.xlsx|所有文件(*.*)|*.*";
         dig.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
         if (dig.ShowDialog() == DialogResult.OK)
         {
             string path = dig.FileName;
             NPOIExcelHelper.Export(GridView, path, true);
             MessageBox.Show("导出成功");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("保存到电子表格时出现错误!");
     }
 }