0

I have a HTML page. This has a grid created using DIV tags and display property set as table and inner DIV's having display properties as table-row and table-cell. If I need to export such table to excel, is there a way to do it in JavaScript? As of now only way I could think of is rewriting those DIV into html TABLE tags.

<div class="tablediv" id="tablediv">
<div class="tablerow">
<div class="tablecell">
A
</div>
<div class="tablecell">
B
</div>
</div>

<div class="tablerow">
<div class="tablecell">
1
</div>
<div class="tablecell">
2
</div>
</div>
</div>

.tablediv {
  display: table;
}
.tablerow {
  display: table-row;
}
.tablecell {
  display: table-cell;
}
fcmaine
  • 359
  • 2
  • 5
  • 17
  • Possible duplicate of [HTML Table to Excel Javascript](https://stackoverflow.com/questions/17126453/html-table-to-excel-javascript) – Bitz Aug 24 '17 at 20:36
  • 1
    @Bitz Answers in those links wouldn't work for this question. As mentioned in the question, grid is not created using html TABLE tag but is created using DIV tags. There is no TABLE tag. When export to excel, such grid doesn't show up as grid in excel. – fcmaine Aug 24 '17 at 20:42

1 Answers1

1

$("#btnExport").click(function(e) {

  //Convert DivTable to Table
   let TBLDiv=$("<div/>",{id:"TBLDivMain"});
   let TBL=$("<table/>");
   let TBO=$("<tbody/>");
   $('#tablediv .tablerow').each(function(key,value){
      let TR=$('<tr/>');
      $(value).find(".tablecell").each(function(key,value){
        let TD=$('<td/>',{text:$(value).text()});
        TR.append(TD);
      });
     TBO.append(TR);
    });
    TBL.append(TBO);
    TBLDiv.append(TBL);
    
    //Export to Excel
    var file = new Blob([TBLDiv.html()], {type:"application/vnd.ms-excel"});
    var url = URL.createObjectURL(file);
    var a = "<a id='Dow' href='"+url+"' download='filename.xls' ></a>";
    $("body").append(a);
    var CickDownload= document.getElementById('Dow');
    CickDownload.click();
    $("body #Dow").remove();
    e.preventDefault();
});
.tablediv {
  display: table;
}
.tablerow {
  display: table-row;
}
.tablecell {
  display: table-cell;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btnExport" value=" Export Table data into Excel " />
<br/>
<br/>

<div class="tablediv" id="tablediv">
    <div class="tablerow">
      <div class="tablecell">A</div>
      <div class="tablecell">B</div>
    </div>
    <div class="tablerow">
       <div class="tablecell">1</div>
       <div class="tablecell">2</div>
    </div>
</div>
Farhad Bagherlo
  • 6,725
  • 3
  • 25
  • 47
  • thanks for the answer. But my table is created using
    's and not . I've now added code to my question.
    – fcmaine Aug 24 '17 at 21:10
  • You can not easily save the **div** in the excel. One method is to read the div,s and create a **runTime** table and then output the same way as above. – Farhad Bagherlo Aug 24 '17 at 21:19