2017年3月13日 星期一

INSERT 後取回最新的 ID

假設有一 [TABLE1],其下欄位為 ID、COLUMN_1 和 COLUMN_2
欄位 ID 設為自動增長

在下了 INSERT 後要取得剛才新增的 ID 時,可以這麼做:
INSERT INTO [TABLE1] (COLUMN_1, COLUMN_2) OUTPUT INSERTED.ID VALUES (DATA1, DATA2)

其中 INSERTED 為 SQL 在建立新資料列時,會暫存的位置,
所以 INSERTED 會找到 [TABLE1] 中的相關資料

同樣的,上述語法也可以用在 UPDATE 上
UPDATE [TABLE1] SET COLUMN_1 = @DATA1, COLUMN_2 = @DATA2 OUTPUT DELETED.ID WHERE ID = 'SomeData'
此時可以取得 UPDATE 是否有影響預期中的資料筆數,可得知是否有更新資料,進而處理下一步(比方:若沒有任何更新表示查詢的資料不存在)
而不需要先查詢有沒有存在,再判斷動作

2017年3月1日 星期三

網頁另開視窗回傳值

【父網頁】

<javascript>

<script>
// 以Post的方式傳值
// url: 開的視窗網址
// name: 開的視窗名稱(可有可無)
// targetid: 回傳後要顯示在哪個元件上
// keys、values: 均以 ['key1','key2']、['value1','value2'] 成對表示
function openWindowWithPost(url, name, targetid, keys, values) {
           
            _targetid = targetid;
            var newWindow = window.open(url, name, "width=" + 600 + "px,height=" + 400 + "px,left=" + 0 + ",top=" + 0);
            //同时将焦点事件绑定,目的是,当点击父窗口时,如果子窗口尚未关闭,那依然回到子窗口,做到类似模式窗口的效果
            window.onfocus = function () { if (newWindow.closed == false) { newWindow.focus(); }; };

            var html = "";
            html += "<html><head></head><body><form id='formid' method='post' action='" + url + "'>";
            if (keys && values && (keys.length == values.length)) {
                for (var i = 0; i < keys.length; i++) {
                    html += "<input type='hidden' name='" + keys[i] + "' value='" + values[i] + "'/>";
                }
            }
            html += "</form><script type='text/javascript'>document.getElementById(\"formid\").submit()<\/script></body></html>";
            newWindow.document.write(html);
            return newWindow;
        }

// 子網頁回傳回來的值在這邊處理
function handleReturnValue(val) {          
            $("#" + _targetid)[0].value = val.join();          
        }
</script>

<html>

<input type="text" id="returnData" >
<input type="button" value="開子視窗" onclick="openWindowWithPost('子視窗的網頁','NewWindowName','returnData',['memberID'],['mem1','mem2'])" />



【子網頁】

<javascript>

<script type="text/javascript">
        // 判斷瀏覽器種類
        function getBrowserType() {
            var Sys = {};
            var ua = navigator.userAgent.toLowerCase();
            if (window.ActiveXObject)
                Sys.ie = ua.match(/msie ([\d.]+)/)[1]
            else if (document.getBoxObjectFor)
                Sys.firefox = ua.match(/firefox\/([\d.]+)/)[1]
            else if (window.MessageEvent && !document.getBoxObjectFor)
                Sys.chrome = ua.match(/chrome\/([\d.]+)/)[1]
            else if (window.opera)
                Sys.opera = ua.match(/opera.([\d.]+)/)[1]
            else if (window.openDatabase)
                Sys.safari = ua.match(/version\/([\d.]+)/)[1];

            if (Sys.ie) return "IE";
            if (Sys.chrome) return 'Chrome';
            if (Sys.firefox) return "Firefox";
            if (Sys.opera) return "Opera";
            if (Sys.safari) return "Safari";

            return "IE";
        }

        // 當關閉子網頁後,要做的動作
        function closeWindow() {    
            // val: 為要回傳給父網頁的物件(或值)    
            var val = $("#cbxMembers input:checked").map(function(){
                return $(this).val();
            }).get();  // 回傳父視窗的值          
           
            if ("IE" == getBrowserType())
                self.returnValue = val;   //IE:直接回傳
            else
                window.opener.handleReturnValue(val); //非IE,調用父視窗的函數來回傳值
            self.close();
        }
    </script>

<html>

<input type="button" value="確定"<input type="button" name="button1" value="確定" onclick="closeWindow();" />


參考:
http://www.weibo.com/p/230418671432cf0102v6rf?pids=Pl_Official_CardMixFeed__4&feed_filter=1

http://www.blogjava.net/kait/archive/2011/05/27/351138.html

2017年1月16日 星期一

Excel 巨集 - 開啟檔案→修正

Sub 巨集1()
'
' 巨集1 巨集
'

'
    For i = 1 To 11
        n = Right(String(2, "0") & i, 3)
        Workbooks.Open Filename:="C:\Users\Min\Downloads\TEMP\TEST_" & n & ".csv"
        Range("B1").Select
        ActiveCell.FormulaR1C1 = "新欄位名稱1"
        Range("D1").Select
        ActiveCell.FormulaR1C1 = "新欄位名稱2"
        Range("F1").Select
        ActiveCell.FormulaR1C1 = "新欄位名稱3"
        Range("F2").Select
        Cells.Replace What:="=-不分區", Replacement:="000-不分區", LookAt:=xlPart, _
            SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
            ReplaceFormat:=False
        ChDir "C:\Users\Min\Downloads\TEMP"
        ActiveWorkbook.SaveAs Filename:= _
            "C:\Users\Min\Downloads\TEMP\TEST_" & n & ".xlsx", FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False
    Next i
End Sub

2016年12月16日 星期五

ASP.NET TreeView 的資料建立

首先要有一父子架構的資料表

Private void SetTree()
{
    // 取得有父子架構的資料
    DataTable dt = GetData("Select ID, Name, FatherID From MyTable");
    // 跑第一層迴圈建立根節點
    foreach (DataRow row in dt.Rows)
    {
           TreeNode root = new TreeNode(rows["ID"].ToString(), rows["Name"].ToString());
           AddChildNode(dt, root);
           TreeView1.Nodes.Add(root);
    }
}

// 跑遞迴建立子節點
Private void AddChildNode(DataTable dt, TreeNode node)
{
    DataRow[] Rows = dt.Select(string.Format("FatherID = {0}", node.Value));  
    if (rows.Count() > 0)
    {
        foreach (DataRow row in Rows)
        {
            TreeNode newNode = new TreeNode(row["ID"].ToString(), rows["Name"].ToString());
            node.ChildNodes.Add(newNode);
            AddChildNode(dt, newNode);
        }
    }
}

使用ASP.NET 的 AJAX 時,顯示 Loading 字樣

HTML 部份
<asp:ScriptManager runat="server">
</asp:ScriptManager>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
    <div class="modal">
        <div class="center">
            <img alt="" src="loader.gif" />
        </div>
    </div>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>

.CS 部份
仍然依照原先的寫法
protected void Button1_Click(object sender, EventArgs e)
{
    GetSomeData();
}

樣式的部份
<style type="text/css">
body
{
    margin0;
    padding0;
}
.modal
{
    positionfixed;
    z-index999;
    height100%;
    width100%;
    top0;
    background-colorBlack;
    filteralpha(opacity=60);
    opacity0.6;
    -moz-opacity0.8;
}
.center
{
    z-index1000;
    margin300px auto;
    padding10px;
    width130px;
    background-colorWhite;
    border-radius10px;
    filteralpha(opacity=100);
    opacity1;
    -moz-opacity1;
}
.center img
{
    height128px;
    width128px;
}
</style>

2016年11月9日 星期三

Excel 巨集 - 自動編號

假設有一資料夾,每個檔案都要在第一個欄位塞入自動編號的值


Sub 新增第一欄為唯一序號()
'
' 新增第一欄為唯一序號 巨集
' 在Excel最左邊加上一新的欄位並給予唯一序號
'

'
For i = 2011 To 2016
    Workbooks.Open Filename:= _
        "C:\Users\Downloads\要加上自動編號\" & i & "NewData.xlsx"
    Columns("A:A").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("A1").Select  '選擇 A1
    ActiveCell.FormulaR1C1 = "唯一值" ' 填入欄位名稱
    Range("A2").Select  '選擇 A2
    ActiveCell.FormulaR1C1 = "1"  '填入數字 1
    Range("A3").Select  '選擇 A2
    ActiveCell.FormulaR1C1 = "2"  '填入數字 2
    Range("A2:A3").Select  '選擇 A2和 A3
' 以上的動作都是用錄製的
    n = ActiveCell.CurrentRegion.Rows.Count ' 找到目前指定的cell的最大列數
    Range("A3").Activate
    Selection.AutoFill Destination:=Range("A2:A" & n)
    Range("A2:A" & n).Select
    ActiveWorkbook.Save
    ActiveWorkbook.Close
Next i
End Sub

2016年10月11日 星期二

Html 上的 Table 匯出成 xls

HTML 部分

若 Table 中的某儲存格會有斷行的情況,則需在網頁的斷行語法加上特定的樣式  (mso-data-placement:same-cell;) 如下
<html>
<table id="myTable">
  <tr>
    <td>第一列第一欄<td>
    <td>第一列第二欄<td>
    <td>第一列第三欄<td>
  </tr>
  <tr>
    <td>
第二列第一欄第一行<br style='mso-data-placement:same-cell;'/>
第二列第一欄第二行
    <td>
    <td>第二列第二欄<td>
    <td>第二列第三欄<td>
  </tr>
  <tr>
    <td>第三列第一欄<td>
    <td>第三列第二欄<td>
    <td>第三列第三欄<td>
  </tr>
</table>
</html>
<input id="btnExport" onclick="ExportTable('myTable'); return false;" type="button" value="另存成 Excel" />


<解決方法一>
下列語法可將網頁上的特定 Table 下載為 Excel
<script>
function ExportTable(tableid)
        {
            var data_type = 'data:application/vnd.ms-excel';
            var table_html = $(tableid)[0].outerHTML.replace(/ /g, '%20');

            var a = document.createElement('a');
            a.href = data_type + ', ' + table_html;
            a.download = '下載.xls';
            a.click();
        }
</script>

<解決方法二> 個人偏好這個方式
<script>
        var table_print;
        function ExportTable(tableid, removeLastColCount) {
            //getting data from our table
            table_print = $('#' + tableid)[0].cloneNode(true);  // copy 一份畫面上的table,再針對這個table 做處理
            deleteColumn(removeLastColCount);
            tableToExcel(table_print, '')
        }

        // 刪除倒數幾欄 (因為多個欄位是功能欄)
        function deleteColumn(lastColCount) {
            for (var i = 0; i < table_print.rows.length; i++) {
                for (var k = 0; k < lastColCount; k++) {
                    // 刪除最後一欄(因為有合併列,所以只能用這個方式)
                    table_print.rows[i].deleteCell(table_print.rows[i].cells.length - 1);
                    //table_print.rows[i].cells[table_print.rows[i].cells.length - 1].innerHTML = "";
                }
            }
        }

        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"><meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8"><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 border="1px">{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)
                var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
                window.location.href = uri + base64(format(template, ctx))
            }
        })()

    </script>

參考來源:http://stackoverflow.com/questions/36040942/how-to-export-a-html-table-to-excel-supported-by-chrome-and-ie