1. 程式人生 > >C#導入導出Excel(一)

C#導入導出Excel(一)

bject gpo tel collect lean type close 表格 excel導入

C#操作Excel導入導出方法一,根據項目要求,對Excel操作有多重方法,有的是類庫自己編程設計格式,有的是JS根據表格的格式樣式直接導出。

現在介紹的是直接下載型:

根據頁面顯示的表格中Html格式,直接下載到Excel(相當於把整個表格直接拷貝到Excel中)

Html格式如下:

  <div id="ta">
            <input type="button" class="btn btn-primary btn-mini" onclick="javascript: method1(‘tableExcel‘)" value="導出Excel">
            <table id="
tableExcel" class="table table-hover"> <thead> <tr> <th>Id</th> <th colspan="2">UserName</th> <th>Email</th> <th>Address</th> <th>Mobile</th> <th>CreateDate</th> <th>操作</th> </tr> </thead> <tbody> @foreach (
var u in ViewBag.Users) { <tr> <td>@u.UserId</td> <td>@u.UserName</td> <td>@u.UserName</td> <td>@u.Email</td> <td>@u.Address</td> <td>@u.Mobile</td> <td>@u.CreateDate</td> <td><a href="
@Url.Action("Delete", "Home")[email protected]" onclick="javascript:return p_del()">Delete</a></td> </tr> } </tbody> </table> </div>

圖例:

技術分享圖片

導出JS:

 function method1(tableid) {//整個表格拷貝到EXCEL中

        //var len = $("table tr").length;
        //if (len > 1) {
        //    $("tr[id=‘" + (len - 1) + "‘]").remove();
        //}
        //$(‘table>th:last‘).hide();
        //$(‘table>td:last‘).hide();
        //var len = $("table tr").length;
        $("table tr th:last-child").remove();
        $("table tr td:last-child").remove();
        
       
        if (getExplorer() == ie) {
            var curTbl = document.getElementById(tableid);
            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 fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
            } catch (e) {
                print("Nested catch caught " + e);
            } finally {
                oWB.SaveAs(fname);

                oWB.Close(savechanges = false);
                //xls.visible = false;
                oXL.Quit();
                oXL = null;
                //結束excel進程,退出完成
                //window.setInterval("Cleanup();",1);
                idTmr = window.setInterval("Cleanup();", 1);

            }

        }
        else {
            tableToExcel(tableid)
        }
    }
    function Cleanup() {
        window.clearInterval(idTmr);
        CollectGarbage();
    }
    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) {


            if (!table.nodeType) table = document.getElementById(table)
            //$(‘table>th:last‘).hide();
            //$(‘table>td:last‘).hide();
            var ctx = { worksheet: name || Worksheet, table: table.innerHTML }
            window.location.href = uri + base64(format(template, ctx))
            parent.$("#ta").load(window.location.href + " #ta");
            parent.subWindow_add.Close();
        }
       
    })()
 

如果導出出現亂碼問題:

解決方案:

添加

<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<meta name="Generator" content="EditPlus">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">

導出的Excel:

技術分享圖片

這裏使用的數據都是在數據庫中讀取,如果實現可以自己修改Html,添加數據,自行測試。

源碼一並在下一章節!!!!

C#導入導出Excel(一)