2015年12月31日 星期四

CSS省略文字及JavaScript判斷是否有省略

有時候為了版面美觀,會將過長的文字敘述隱藏而使用ToolTip的方式顯示,但當文字並沒有被隱藏卻顯示ToolTip則顯得有點多餘,因此分享以下的判斷方式做為參考。

<style>
   
table{
       
margin: 1em;
    }
    .
row div {
       
padding: 5px;
    }
   
/** 透過CSS設定將長度大於100px的內容隱藏 **/
   
.shortern div{
       
width: 100px;
       
overflow: hidden;
       
text-overflow: ellipsis;
       
white-space: nowrap;
    }
    .
tip{
       
background: black;
       
color: white;
       
font-weight: bold;
       
padding: 5px;
    }
</
style>

<div class="row">

    <table class="shortern" border="1">

        <tr>

            <td>

                <div>Something is very looooong</div>

            </td>

        </tr>

        <tr>

            <td>

                <div>Short</div>

            </td>

        </tr>

    </table>

</div>

<div class="row tip" style="position: absolute">

    <!--I am tooltip;-->

</div>


<script>

    $(document).ready(function(){

        var $tooltip=$(".tip");

        $tooltip.hide();

        $("table div").hover(function(e){

            var targetEle = e.target;

            var $target = $(targetEle);

            /**

             * 判斷ElementscrollWidth是否大於offsetWidth

             * 較大則代表有被隱藏的文字

             * **/

            if(targetEle.scrollWidth > targetEle.offsetWidth){

                var offset = $target.offset();

                offset.left = offset.left + $(targetEle).parent().width() + 30;

                offset.top = offset.top;

                $tooltip.css(offset);

                $tooltip.text($(this).text());

                $tooltip.show();

            }

        },function(e){

            $tooltip.hide();

        })

    });

</script>

Javascript 產出XLSX

先前已分享過Javascript產出Excel IE主要是透過ActiveXObject來執行Script,而非IE瀏覽器則是透過HTML的內容假裝是XLS檔案來匯出,若碰到IE被限制ActiveXObject不能執行的狀況就無法正常產出。

因此進一步找了一個JSlib-- js-xlsx (簡單易懂的名稱),是Open Source,可直接透過瀏覽器讀取用戶端的檔案而不需要透過Server 進行。

可讀取的檔案格式:
·      Excel 2007+ XML Formats (XLSX/XLSM)
·      Excel 2007+ Binary Format (XLSB)
·      Excel 2003-2004 XML Format (XML "SpreadsheetML")
·      Excel 97-2004 (XLS BIFF8)
·      Excel 5.0/95 (XLS BIFF5)
·      OpenDocument Spreadsheet (ODS)
寫入的檔案格式:
·      XLSX
·      CSV (and general DSV)
·      JSON and JS objects (various styles)

GitHub:
https://github.com/SheetJS/js-xlsx

lib主要是進行檔案內容的讀取及寫入,若要能下載則需要搭配另外的JS Lib,因此共需要的lib如下。
·         Blob.js  http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js
·         FileSaver.js http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js
·         Export2Excel.jscopy from http://sheetjs.com/demos/table.html
·         xlsx.core.min.jshttps://github.com/SheetJS/js-xlsx

以下提供簡單範例


<table id="export">
    <
tr>
        <
td>Number</td>
        <
td>Name</td>
        <
td>Gender</td>
        <
td>Age</td>
    </
tr>
    <
tr>
        <
td>1</td>
        <
td>Mary</td>
        <
td>Female</td>
        <
td>48</td>
    </
tr>
    <
tr>
        <
td>2</td>
        <
td>Paul</td>
        <
td>Male</td>
        <
td>18</td>
    </
tr>
</
table>
<
button id="exportBtn">Export</button>
<
script>
   
$(document).ready(function(){
      
$("#exportBtn").click(function(){
          
//將需要轉成ExcelTable取出
          
var exportTable = document.getElementById("export");
          
//匯出成Excel,此功能略有調整,原本傳的是ID,改為傳TableElement較方便
          
export_table_to_excel(exportTable,"ExportExcel.xlsx");
       });
    });
</
script>

2015年11月2日 星期一

Javascript產出Excel

有時碰到有些資料表(Data Grid)因為Server Side運算時間很久或資料量大 

便不希望再次由Server端回傳Excel 

而既然瀏覽器端上已經有運算結果的資料,就可直接用來產生Excel檔案,因此找了一個適用於IEChrome的處理方法,紀錄一下。 

其概念在非IE的瀏覽器上,透過HTML<a>將檔案回傳,類似以下的結構 

<a 
download="fileName.xls" href="data:application/vnd.ms-excel;base64,(base64編碼)"></a> 

其中只是將資料表以Html Table的字串方式透過base64編碼。 

而在IE的瀏覽器上則是透過ActiveXObject直接開啟Excel並直接使用Script產出結果,還滿有意思的~可以試試看!(雖然又被IE玩了一次....)

function exportExcel(){
    // Html Table資料
   
var table = "<table>" +
                   
"<tr><th>Name</th><th>Age</th><th>Score</th></tr>" +
                   
"<tr><td>Scott</td><td>13</td><td>90</td>" +
                   
"<tr><td>Tiger</td><td>14</td><td>70</td></tr>" +
               
"</table>";
                 // IE11後的ActiveXObject判斷方式不同...
   
var isIE = window['ActiveXObject'] || "ActiveXObject" in window ? 
               true : false;
   
if (!isIE) {
       
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><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8"><!--[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];
                })
            };

       
var ctx = {worksheet: 'Worksheet', table: table.innerHTML};
       
var a = document.createElement('a');
       
a.href= uri + base64(format(template, ctx));
       
a.download=reportMaster.reportName+".xls";
       
a.click();
   
} else {
       
var i, j, str,
           
rowCount = table.rows.length,
            // Activates Excel
           
excel = new ActiveXObject('Excel.Application');
        // Opens a new Workbook
       
excel.Workbooks.Add(); 
        // Shows Excel on the screen
       
excel.Application.Visible = true;
       
for (i = 0; i < rowCount; i++) {
           
for (j = 0; j < table.rows[i].cells.length; j++) {
               
str = table.rows[i].cells[j].innerText;
               
if(str!==null&&str!=='undefined'){
                    // Writes to the sheet
                   
excel.ActiveSheet.Cells(i + 1, j + 1).Value = str
                }
                   
           
}
        }
    }
}