Modj
Modj

Reputation: 35

Set condition for innerHTML of a table

I have a Table, this table is imported from a excel file using this HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>XLSX to HTML</title>
    <link rel="stylesheet" href="css/style.css" type="text/css"/>
    <script src='http://alasql.org/console/xlsx.core.min.js'></script>
    <script src='http://alasql.org/console/alasql.min.js'></script>
</head>
<body>
    <script>
        alasql('select * into html("#here",{headers:true}) \
          from xlsx("data/data.xlsx",\
                    {headers:true})');
    </script>
    <div id="here"></div>
</body>
</html>

My excel file contains 4 columns and 23 rows. Value of 4th column is equal to subtracting 2nd column from 3rd column.
Now I want to set a condition for 4th column. if value is greater than 0 (zero) set the specific box color related to that td to green, if value is equal 0 set it to yellow and if its smaller than 0 (negative value) set the color to Red.
I would be grateful if you help get through this. I just know HTML + CSS Basics.

Upvotes: 0

Views: 935

Answers (1)

agershun
agershun

Reputation: 4107

You can modify your code and generate HTML table yourself without using Alasql's INTO HTML() function. See the example below:

// First: read data from XLSX file into "res" variable
alasql('select * from xlsx("data/data.xlsx", {headers:true})',function(res){
    // Start to create HTML text 
    var s = '<table><thead><th>Col1<th>Col2<tbody>'; // Generate table header
    for(var i=0;i<res.len;i++) {
        s += '<tr>';
        s += '<td>'+res[i].Col1;    // Cell for first column
        s += '<td ';
        // Now add colored cell for second column
        if(res[i].Col2>0) s += 'style="background-color:yellow"';
        else s += 'style="background-color:red"';
        s += '>'+res[i].Col2;
    }
    s += '</table>';
});
document.getElementById('res').innerHTML = s;

See the working snippet below with a concept of coloring table cells.

Disclaimer: I am author of Alasql.

   var res = [{a:1,b:1},{a:2,b:-1}];
   var s = '<table><thead><th>Col1<th>Col2<tbody>';
        for(var i=0;i<res.length;i++) {
            s += '<tr>';
            s += '<td>'+res[i].a;
            s += '<td ';
            if(res[i].b>0) s += 'style="background-color:yellow"';
            else s += 'style="background-color:red"';
            s += '>'+res[i].b;
        }
        s += '</table>';

    document.getElementById('res').innerHTML = s;
<div id="res"></div>

Upvotes: 2

Related Questions