• Excel导出


    <!DOCTYPE html>
    <html>
    <head>
        <title>ASP.NET版Memcached监控工具</title>
        <style type="text/css">
            ul
            {
                list-style: none;
            }
            li
            {
                width: 200px;
                height: 150px;
                float: left;
                margin-right: 10px;
                margin-bottom:10px;
            }
            li span
            {
                display: block;
                width: 200px;
            }
            li img
            {
                width: 200px;
                height: 100px;
            }
        </style>
        <script type="text/javascript">
    
            (function (bool) {
                function setInnerText(o, s) {
                    while (o.childNodes.length != 0) {
                        o.removeChild(o.childNodes[0]);
                    }
    
                    o.appendChild(document.createTextNode(s));
                }
    
                function getInnerText(o) {
                    var sRet = "";
    
                    for (var i = 0; i < o.childNodes.length; i++) {
                        if (o.childNodes[i].childNodes.length != 0) {
                            sRet += getInnerText(o.childNodes[i]);
                        }
    
                        if (o.childNodes[i].nodeValue) {
                            if (o.currentStyle.display == "block") {
                                sRet += o.childNodes[i].nodeValue + "
    ";
                            } else {
                                sRet += o.childNodes[i].nodeValue;
                            }
                        }
                    }
    
                    return sRet;
                }
    
                if (bool) {
                    HTMLElement.prototype.__defineGetter__("currentStyle", function () {
                        return this.ownerDocument.defaultView.getComputedStyle(this, null);
                    });
    
                    HTMLElement.prototype.__defineGetter__("innerText", function () {
                        return getInnerText(this);
                    })
    
                    HTMLElement.prototype.__defineSetter__("innerText", function (s) {
                        setInnerText(this, s);
                    })
                }
            })(/Firefox/.test(window.navigator.userAgent));
    </script>
    
        <script type="text/javascript">
            function innerText(node) {//返回的是数组类型
                var innerTextArr = [];
                var root = document.getElementById(node);
                var getChild = function (node) {
                    var childs = node.childNodes;
                    for (var i = 0; i < childs.length; i++)
                        if (childs[i].nodeType == 3)
                            innerTextArr.push(childs[i].nodeValue);
                        else if (childs[i].nodeType == 1) {
                            getChild(childs[i]);
                        }
                }
                getChild(root);
                return innerTextArr;
            }
            window.onload = function () {
                var _ul = document.getElementById('oUl');
                var _li = _ul.getElementsByTagName('li');
                var _total = 0;
                for (var i = 0, l = _li.length; i < l; i++) {
                    var _img = _li[i].getElementsByTagName('img')[0];
                    
                    _img.onclick = function () {
                        var _spans = this.parentNode.getElementsByTagName('span');
                        var _js = parseInt(_spans[0].innerText);
                        _spans[0].innerText = _js + 1;
                        var _cs = parseInt(_spans[1].innerText);
                        _spans[2].innerText = (_js + 1) * _cs;
                        _total += _cs;
                        document.getElementById('hj').value = _total;
                    }
    
                }
    
            };
            function dcExcel() {
                var doc = document;
                var _ul = doc.getElementById('oUl');
                var _li = _ul.getElementsByTagName('li');
                var _jsonstr = "";
                var _total = 0;
                for (var i = 0, l = _li.length; i < l; i++) {
                    var _img = _li[i].getElementsByTagName('img')[0];
                    _jsonstr += ",{";
                    _jsonstr += '"img":"' + _img.getAttribute("src") + '"';
                    
                    
                    
                        var _spans = _img.parentNode.getElementsByTagName('span');
                        var _js = parseInt(_spans[0].innerText);
                        //_spans[0].innerText = _js + 1;
                        _jsonstr += ',"num":"' + _js + '"';
    
                        var _cs = parseInt(_spans[1].innerText);
                        _jsonstr += ',"dj":"' + _cs + '"';
                        
                        //_spans[2].innerText = (_js + 1) * _cs;                    
                        _jsonstr += ',"hj":"' + (_js * _cs) + '"';
                        _total += _cs;
                        //doc.getElementById('hj').value = _total;
                        _jsonstr += "}";
    
                    }
                    //alert(_jsonstr);
                    document.getElementById("txt_excel").value = encodeURIComponent("[" + _jsonstr.substr(1) + "]");
                //document.getElementById("txt_excel").value = encodeURIComponent(document.getElementById("divDC").innerHTML);
            }
        </script>
    
    </head>
    <body>
    <form method="post" runat="server" action="dc.aspx">
    <textarea id="txt_excel" name="txt_excel" style="display:none;"></textarea>
        <input type="submit" value="Excel导出" onclick="dcExcel();" />
        </form>
        <div id="divDC">
        合计:<input type="text" id="hj" value="0" readonly="readonly" />
        <input type="button" value="清空" onclick="location.reload()" />
        <ul id="oUl">
            <li>
                <img src='newimage/1.jpg' alt='1' />
                <span>0</span> <span>3</span> <span></span></li>
            <li>
                <img src='newimage/1.jpg' alt='2' />
                <span>0</span> <span>5</span> <span></span></li>
            <li>
                <img src='newimage/1.jpg' alt='3' />
                <span>0</span> <span>6</span> <span></span></li>
            <li>
                <img src='newimage/1.jpg' alt='4' />
                <span>0</span> <span>9</span> <span></span></li>
            <li>
                <img src='newimage/1.jpg' alt='5' />
                <span>0</span> <span>7</span> <span></span></li>
            <li>
                <img src='newimage/1.jpg' alt='6' />
                <span>0</span> <span>2</span> <span></span></li>
        </ul>
        </div>
    </body>
    </html>
    dc.aspx

    using System;
    using System.Web;
    using System.Data;
    using System.IO;
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Reflection;
    using System.Diagnostics;
    using Newtonsoft.Json;
    
    
    public partial class dc : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string _productsInfo = Server.UrlDecode(Request.Form["txt_excel"]);
            JavaScriptArray javascript = (JavaScriptArray)JavaScriptConvert.DeserializeObject(_productsInfo);
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("img", typeof(System.String)));
            dt.Columns.Add(new DataColumn("num", typeof(System.String)));
            dt.Columns.Add(new DataColumn("dj", typeof(System.String)));
            dt.Columns.Add(new DataColumn("hj", typeof(System.String)));
            if (javascript.Count > 0)
            {
                DataRow dr;
                foreach (JavaScriptObject obj in javascript)
                {
                    dr = dt.NewRow();
                    dr["img"] = obj["img"].ToString();
                    dr["num"] = obj["num"].ToString();
                    dr["dj"] = obj["dj"].ToString();
                    dr["hj"] = obj["hj"].ToString();
                    dt.Rows.Add(dr);
                }
            }
            btntoexcel_Click(dt);
            //byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
            
            //string fileName = strName;//客户端保存的文件名
            //string filePath = Server.MapPath(strPath);//路径 
            ////以字符流的形式下载文件
            //FileStream fs = new FileStream(filePath, FileMode.Open);
            //byte[] bytes = new byte[(int)fs.Length];
            //fs.Read(bytes, 0, bytes.Length);
            //fs.Close();
            /*
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment;  filename=" + 
                HttpUtility.UrlEncode(DateTime.Now.ToShortTimeString() + ".txt", System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            */
    
    
    
    
    
    
    
    
            /*
            NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
            NPOI.SS.UserModel.Sheet sheet = book.CreateSheet("order");
            
            NPOI.SS.UserModel.Row row = sheet.CreateRow(0);
            //订单表设置标题
            row.CreateCell(0).SetCellValue(str);
            
    
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            book.Write(ms);
            HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=Order_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls"));
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            book = null;
            ms.Close();
            ms.Dispose();
            */
        }
    
        #region 导出
        private void btntoexcel_Click(System.Data.DataTable dt)
        {
            if (dt != null)
            {
                #region 操作excel
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                xlWorkBook = new Excel.Application().Workbooks.Add(Type.Missing);
                xlWorkBook.Application.Visible = false;
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
                //设置标题
                xlWorkSheet.Cells[1, 1] = "数量";
                xlWorkSheet.Cells[1, 2] = "单价";
                xlWorkSheet.Cells[1, 3] = "合计";
                xlWorkSheet.Cells[1, 4] = "图片";
                //设置宽度            
                ((Excel.Range)xlWorkSheet.Cells[1, 2]).ColumnWidth = 15;
                ((Excel.Range)xlWorkSheet.Cells[1, 4]).ColumnWidth = 50;//图片的宽度
    
                //设置字体
                xlWorkSheet.Cells.Font.Size = 12;
                xlWorkSheet.Cells.Rows.RowHeight = 100;
                #region 为excel赋值
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //为单元格赋值。
                    xlWorkSheet.Cells[i + 2, 1] = dt.Rows[i]["num"].ToString();
                    xlWorkSheet.Cells[i + 2, 2] = dt.Rows[i]["dj"].ToString();
                    xlWorkSheet.Cells[i + 2, 3] = dt.Rows[i]["hj"].ToString();
    
                    #region
                    //可以直接取图片的地址
                    string filename = Server.MapPath("~/" + dt.Rows[i]["img"].ToString());
                    //也可以用下面的方法把图片从数据库里取出来。
                    //byte[] filedata = (byte[])dtimg.Rows[j]["img"];
                    //System.IO.MemoryStream ms = new System.IO.MemoryStream(filedata);
                    //System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
                    //img.Save(filename);
                    #endregion
                    //int rangeindex = i+1;
                    //string rangename = "D" + rangeindex;
                    //Excel.Range range = xlWorkSheet.get_Range(rangename, Type.Missing);
                    //range.Select();
                    //Excel.Pictures pict = (Excel.Pictures)xlWorkSheet.Pictures(Type.Missing);
                    //pict.Insert(filename, Type.Missing);
    
                    //Left , Top , Width and Height.
                    xlWorkSheet.Shapes.AddPicture(filename, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue,
                        220, 100 + i * 100, 100, 100);
    
    
                }
                #endregion
                #region 保存excel文件
                string _sj = DateTime.Now.ToString("yyyyMMddHHmmss");
                string filePath = Server.MapPath("/") + _sj + "导出.xls";
                xlWorkBook.SaveAs(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                xlWorkBook.Application.Quit();
                xlWorkSheet = null;
                xlWorkBook = null;
                GC.Collect();
                System.GC.WaitForPendingFinalizers();
                #endregion
                #endregion
                KillProcessexcel("EXCEL");
    
                #region 导出到客户端
                /*
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                Response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode("导出", System.Text.Encoding.UTF8) + ".xls");
                Response.ContentType = "Application/excel";
                Response.WriteFile(filePath);
                Response.End();
                */
                #endregion
    
                Response.ContentType = "application/octet-stream";
                //通知浏览器下载文件而不是打开
                Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(filePath, System.Text.Encoding.UTF8));
                //Response.BinaryWrite(bytes);
                Response.WriteFile(filePath);
                Response.Flush();
    
                File.Delete(filePath);
    
                Response.End();
            }
        }
        #endregion
        #region 杀死进程
        private void KillProcessexcel(string processName)
        { //获得进程对象,以用来操作
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();
            //得到所有打开的进程
            try
            {
                //获得需要杀死的进程名
                foreach (Process thisproc in Process.GetProcessesByName(processName))
                { //立即杀死进程
                    thisproc.Kill();
                }
            }
            catch (Exception Exc)
            {
                throw new Exception("", Exc);
            }
        }
        #endregion
    }
  • 相关阅读:
    android.mk 文件中变量
    【转】An Intuitive Guide To Exponential Functions & e
    卷积相关
    opencv 调试时不显示图像
    Luhn 算法-- 信用卡号码的校验
    perl 脚本实现简单搜索修改文件并生成diff文件
    【转】gcc: multiple definition of [转]
    【转】undefined reference问题总结
    【转】pthread_cond_t怎么使用
    linux编程使用记录
  • 原文地址:https://www.cnblogs.com/daixingqing/p/3497437.html
Copyright © 2020-2023  润新知