zoukankan      html  css  js  c++  java
  • 后台导出EXCEL文档

    导出这里有两个一个是直接数据库查到数据后导出,一个是到页面点击下载导出


    1.到数据库查询需要打印的数据,改为DataSet类型传入下面的方法

    2.这个自动生成后地址为:我的文档

       #region DataSetToExcel
            public static bool DataSetToExcel(DataSet dataSet, bool isShowExcle)
            {
                try
                {
                    System.Data.DataTable dataTable = dataSet.Tables[0];
                    int rowNumber = dataTable.Rows.Count;//条数
                    int columnNumber = dataTable.Columns.Count;//列数
                    int colIndex = 0;
    
                    if (rowNumber == 0)
                    {
                        LogHelper.WriteErrorLog(string.Format("DataSetToExcel:rowNumber:{0},DateTime:{1},dataSet:{2}", rowNumber, DateTime.Now, dataSet));
                        return false;
                    }
    
                    //建立Excel对象 
                    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                    Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
                    excel.Visible = isShowExcle;
                    Microsoft.Office.Interop.Excel.Range range;
    
                    //生成字段名称 
                    foreach (DataColumn col in dataTable.Columns)
                    {
                        colIndex++;
                        excel.Cells[1, colIndex] = col.ColumnName;
                    }
    
                    object[,] objData = new object[rowNumber, columnNumber];
                    //遍历
                    for(int i=0;i<rowNumber;i++)
                    {
                        for(int j=0;j<columnNumber;j++)
                        {
                            objData[i, j] = dataTable.Rows[i][j];
                        }
                    }
                    // 写入Excel 
                    range = worksheet.Range[excel.Cells[2, 1], excel.Cells[rowNumber + 1, columnNumber]];
                    //range.NumberFormat = "@";//设置单元格为文本格式 
                    range.Value2 = objData;
                    worksheet.Range[excel.Cells[2, 1], excel.Cells[rowNumber + 1, 1]].NumberFormat = "yyyy-m-d h:mm";
    
                    return true;
                }
                catch (Exception ex)
                {
                    LogHelper.WriteErrorLog(string.Format("DataSetToExcel:ex:{0},DateTime:{1}", ex, DateTime.Now));
    
                    return false;
                }
            }
    
            #endregion

    (一).导出满足条件的数据

    1.操作页面创建方法实现后台操作,页面方法如下

       <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
            <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">XX记录</a></li>
            <li><label onclick="javascript:excelsA()" style="color:azure;" id="label1">&emsp;导出数据EXCEL</label></li>
        </ul>
        <script type="text/javascript">
            var count = 0;
            function labelA() {
                alert("请稍等数据量较大,正在努力导出!");
            }
    
            function excelsA() {
                if (count == 0) {
                    alert("请等待,注:生成中请勿重复点击!");
                    count++;
                    $.ajax({
                        type: "POST",
                        url: "GetExcel",
                        contentType: "application/json; charset=utf-8",
                        data: "{Type:'EG',Time1:'" + document.getElementById("BetTime1").value + "',Time2:'" + document.getElementById("BetTime2").value + "'}",
                        success: function (msg) {
                            count = 0;
                            if (msg.indexOf("该时间段:") >= 0)
                            { alert(msg); }
                            else
                            { excels(msg); }
                        }
                    });
                } else {
                    $("#label1").click(labelA);//防止导出时多次操作
                }
            }
    
    
            var timer;
            function getExplorer() {//获取浏览器
                var explorer = window.navigator.userAgent;
                if (explorer.indexOf("MSIE") >= 0 || (explorer.indexOf("Windows NT 6.1;") >= 0 && explorer.indexOf("Trident/7.0;") >= 0)) {
                    return 'ie';
                } else if (explorer.indexOf("Firefox") >= 0) {
                    return 'Firefox';
                } else if (explorer.indexOf("Chrome") >= 0) {
                    return 'Chrome';
                } else if (explorer.indexOf("Opera") >= 0) {
                    return 'Opera';
                } else if (explorer.indexOf("Safari") >= 0) {
                    return 'Safari';
                }
            }
    
            function excels(table) {
                if (getExplorer() == 'ie') {
                    var curTbl = document.getElementById(table);
                    var oXl = new ActiveXObject("Excel.Application");//创建AX对象excel
                    var oWB = oXL.Workbooks.Add();//获取workbook对象
                    var xlsheet = oWB.Worksheets(1);//激活当前sheet
                    var sel = document.body.createTextRange();
                    sel.moveToElementText(curTbl);//把表格中的内容移到TextRange中
                    sel.select;//全选TextRange中内容
                    sel.execCommand("Copy");//复制TextRange中内容
                    xlsheet.Paste();//粘贴到活动的EXCEL中
                    oXL.Visible = true;//设置excel可见属性
                    try {
                        var filename = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
                    } catch (e) {
                        window.print("Nested catch caught " + e);
                    } finally {
                        oWB.SaveAs(filename);
                        oWB.Close(savechanges = false);
                        oXL.Quit();
                        oXL = null;//结束excel进程,退出完成
                        timer = window.setInterval("Cleanup();", 1);
                    }
                } else {
                    tableToExcel(table);
                }
            }
    
            function Cleanup() {
                window.clearInterval(timer);
                CollectGarbage();//CollectGarbage,是IE的一个特有属性,用于释放内存的
            }
            var tableToExcel = (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
                    format = function (s, c) {
                        return s.replace(/{(w+)}/g,
                            function (m, p) { return c[p]; })
                    };
                return function (table, name) {
                    debugger;
                    var ctx = { worksheet: name || 'Worksheet', table: table };
                    window.location.href = uri + base64(format(template, ctx))
                }
            })();
    
        </script>

    2.后台操作为

    到数据库查询数据,拼接为HTML代码,也可以加上一些样式

    (二).导出当前页面的数据

    
    
      <ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
            <li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active"><a href="#tabs-1">XX记录</a></li>
    <li><input id="Button1" type="button" value="导出数据EXCEL" onclick="javascript:excels('DataTable')" /></li>
        </ul>
    
        <script type="text/javascript">
            var timer;
            function getExplorer() {//获取浏览器
                var explorer = window.navigator.userAgent;
                if (explorer.indexOf("MSIE") >= 0 || (explorer.indexOf("Windows NT 6.1;") >= 0 && explorer.indexOf("Trident/7.0;") >= 0)) {
                    return 'ie';
                } else if (explorer.indexOf("Firefox") >= 0) {
                    return 'Firefox';
                } else if (explorer.indexOf("Chrome") >= 0) {
                    return 'Chrome';
                } else if (explorer.indexOf("Opera") >= 0) {
                    return 'Opera';
                } else if (explorer.indexOf("Safari") >= 0) {
                    return 'Safari';
                }
            }
            function excels(table) {
                if (confirm("导出当前页数据")) {
                    if (getExplorer() == 'ie') {
                        var curTbl = document.getElementById(table);
                        var oXl = new ActiveXObject("Excel.Application");//创建AX对象excel
                        var oWB = oXL.Workbooks.Add();//获取workbook对象
                        var xlsheet = oWB.Worksheets(1);//激活当前sheet
                        var sel = document.body.createTextRange();
                        sel.moveToElementText(curTbl);//把表格中的内容移到TextRange中
                        sel.select;//全选TextRange中内容
                        sel.execCommand("Copy");//复制TextRange中内容
                        xlsheet.Paste();//粘贴到活动的EXCEL中
                        oXL.Visible = true;//设置excel可见属性
                        try {
                            var filename = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
                        } catch (e) {
                            window.print("Nested catch caught " + e);
                        } finally {
                            oWB.SaveAs(filename);
                            oWB.Close(savechanges = false);
                            oXL.Quit();
                            oXL = null;//结束excel进程,退出完成
                            timer = window.setInterval("Cleanup();", 1);
                        }
                    } else {
                        tableToExcel("DataTable");
                    }
                } else {
                    alert("导出原数据");
                    alert("该功能请稍后");
                } 
            }
            function Cleanup() {
                window.clearInterval(timer);
                CollectGarbage();//CollectGarbage,是IE的一个特有属性,用于释放内存的
            }
            var tableToExcel = (function () {
                var uri = 'data:application/vnd.ms-excel;base64,',
                    template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
                    base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) },
                    format = function (s, c) {
                        return s.replace(/{(w+)}/g,
                            function (m, p) { return c[p]; })
                    };
                return function (table, name) {
                    debugger;
                    if (!table.nodeType) table = document.getElementById(table);
                    var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML };
                    window.location.href = uri + base64(format(template, ctx))
                }
            })();
        </script>
  • 相关阅读:
    SQL Server中的syscomments表 解析
    char(0)引起的sql2000与sql2005结果不一致
    [转]Winform精耕细作DefWndProc/WndProc/IMessageFilter的区别
    C# 操作并口类,并口通信
    [转]计算机存储单位Byte、KB、MB、GB、TB、PB、EB、ZB、YB、DB、NB
    .net 深入系统编程(三)
    网站随记
    集训final D STL中string的应用
    icpc回顾·暑假
    ie中按钮onclick等事件失效。提示提示对象不支持此操作。在谷歌浏览器中又能使用解决办法
  • 原文地址:https://www.cnblogs.com/ZxtIsCnblogs/p/9257753.html
Copyright © 2011-2022 走看看