zoukankan      html  css  js  c++  java
  • 非常简单实用的Excel导出

     1,Html代码:创建导出按钮(使用的是EasyUI插件)

    <a href="javascript:void(0)" onclick="ExportSalesMaterialData()" class="easyui-linkbutton" data-options="iconCls:'icon-download',plain:true">导出查询数据</a></td>
    

     2,JS代码

    function ExportSalesMaterialData() {
                var rows = $('#dg').datagrid('getRows');//dg为Table标签ID
                if (rows.length > 0) {
                    $.messager.confirm('确认', '确定导出数据吗?', function (v) {
                        if (v) {
    
                            $('#form1').form('submit', {
                                url: "MBStatistics.aspx?action=excel&" + $("#form1").serialize(),//form1为form表单ID(例:<form id="form1" method="post"></form>)
                            });
                        }
                    });
                } else {
                    $.messager.alert("提示", "当前没有可导出数据!");
                }
            }

    3,C# 代码

            public void ExportSalesMaterialData() 
            {
                StringBuilder filter = new StringBuilder();//这里为对应表单where条件
                filter.Append(" 1=1 and IsDelete=0 ");//*
                if (!string.IsNullOrWhiteSpace(GetPam("StartTime")))
                {
                    filter.AppendFormat(" and CreateTime >= '{0}'", GetPam("StartTime"));
                }
                if (!string.IsNullOrWhiteSpace(GetPam("EndTime")))
                {
                    filter.AppendFormat(" and CreateTime <= '{0}'", GetPam("EndTime"));
                }
                if (!string.IsNullOrWhiteSpace(GetPam("combProductStatusType")))
                {
                    filter.AppendFormat(" and IsRelated  = '{0}'", GetPam("combProductStatusType"));
                }
    
                string where = filter.ToString();
    //注意:你只需要改sqlStr参数的sql语句,改成你要导出的sql即可
    string sqlStr = string.Format(@" select CreateTime '日期',DrugUsersName '购药人',DrugUsersPhone '手机号',WXNumber '微信', ConfirmedDisease '确诊疾病',DrugName '药品通用名',BrandName '药品品牌',Specifications '急需药品规格', Manufacturer '生产厂家', SurplusQuantity '剩余药品余量',[Address] '药品邮寄地址', Remake '备注', case IsRelated when 1 then '联系' else '无联系' end '是否联系' from ChronicDiseaseRegister WHERE {0} ORDER BY CreateTime desc ", where); string fileName = DateTime.Now.ToString(); Out2Excel(DAL.Base.SqlHelper.ExecuteDataSet("MallCenter", CommandType.Text, sqlStr).Tables[0], fileName); } private void Out2Excel(DataTable dtSource, string fileName) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; HSSFRow dataRow = null; int sheetMaxRowIndex = 65535; int currentRowIndex = 0; //填充内容 for (int i = 0; i < dtSource.Rows.Count; i++) { if (currentRowIndex == 0) { //填充表头 dataRow = sheet.CreateRow(currentRowIndex) as HSSFRow; foreach (DataColumn column in dtSource.Columns) { HSSFCell cell = dataRow.CreateCell(column.Ordinal) as HSSFCell; cell.SetCellValue(column.ColumnName); } currentRowIndex++; } dataRow = sheet.CreateRow(currentRowIndex) as HSSFRow; for (int j = 0; j < dtSource.Columns.Count; j++) { HSSFCell cell = dataRow.CreateCell(j) as HSSFCell; cell.CellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@"); cell.SetCellValue(dtSource.Rows[i][j].ToString()); } currentRowIndex++; if (currentRowIndex > sheetMaxRowIndex) { sheet = workbook.CreateSheet() as HSSFSheet; currentRowIndex = 0; } } //保存 using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); Out2Client(ms, fileName); } } private void Out2Client(MemoryStream ms, string fileName) { byte[] data = ms.ToArray(); if (!fileName.Contains(".xls") || !fileName.Contains(".xlsx")) { fileName += ".xls"; } #region 客户端保存 HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; response.Clear(); response.Charset = "UTF-8"; response.ContentEncoding = System.Text.Encoding.UTF8; response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel"; if (request.UserAgent.ToLower().IndexOf("msie") > -1) { fileName = HttpUtility.UrlPathEncode(fileName); } if (request.UserAgent.ToLower().IndexOf("firefox") > -1) { response.AddHeader("Content-Disposition", "attachment;filename="" + fileName + """); } else { response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); } response.AddHeader("Content-Length", data.Length.ToString()); response.BinaryWrite(data); response.End(); #endregion }

    非常简单易懂,复制即用

  • 相关阅读:
    【转】c#基础系列1---深入理解值类型和引用类型
    【转】Aspnet Core为什么支持跨平台
    [翻译svg教程]svg学习系列 开篇
    使用docker 解决一个小问题,你也可能用的到
    增加软链接
    漫长的表白
    被社会抽了一巴掌
    杂乱五章的2015年终总结
    [资源分享]yslow 与firebug 修复版本Firefox35【绿色版本下载】
    Web前端性能测试-性能测试知多少---深入分析前端站点的性能
  • 原文地址:https://www.cnblogs.com/hq89533921/p/13353443.html
Copyright © 2011-2022 走看看