Div таблица в excel

HtmlTableToExcel

Converting HTML tables to Excel

Install

Library can be installed through Nuget.

PM> Install-Package HtmlTableToExcel

Sample HTML table:

alt text

Excel File:

alt text

Usage

Convert from html table

string html = "<table><tr><th>Name</th><th>Favorite Color</th></tr><tr><td>Bob</td><td>Yellow</td></tr><tr><td>Michelle</td><td>Purple</td></tr></table>";

HtmlTableToExcel tableToExcel = new HtmlTableToExcel();

byte[] converted = tableToExcel.Process(html);

Convert from html div

Use data-export tag for defining table, row and cell

<div data-export="table">
	<div data-export="row">
		<div data-export="cell">Name</div>
		<div data-export="cell">Favorite Color</div>
	</div>
	<div data-export="row">
		<div data-export="cell">Bob</div>
		<div data-export="cell">Yellow</div>
	</div>
	<div data-export="row">
		<div data-export="cell">Michelle</div>
		<div data-export="cell">Purple</div>
	</div>
</div>
string html = "<div data-export='table'><div data-export='row'><div data-export='cell'>Name</div><div data-export='cell'>Favorite Color</div></div><div data-export='row'><div data-export='cell'>Bob</div><div data-export='cell'>Yellow</div></div><div data-export='row'><div data-export='cell'>Michelle</div><div data-export='cell'>Purple</div></div></div>";

var parser = new Parsers.DataAttributeParser();
HtmlTableToExcel tableToExcel = new HtmlTableToExcel(parser);

byte[] converted = tableToExcel.Process(html);

Licence

MIT licence (permits usage in commercial applications)

I was put on this project and the other developer before me used a bunch of divs to create a table. I was put in charge of exporting these tables to Excel. The only problem is that these aren’t normal HTML tables. They are a bunch of divs made to look like a table.

Is there a way to convert the div table look alike to a normal HTML table? Or could I still export this look alike table to excel?

Here’s a quick example

<div>
    <div class="row">
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
    </div>
    <div class="row">
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
    </div>
    <div class="row">
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
    </div>
</div>

asked Aug 10, 2016 at 16:37

2

You could use JavaScript to create a table, loop through all the .row and .column elements in the div to popultate it, remove the div and append the table. Here’s something I threw together very quickly to get you started. (I commented out the line that removes the div so you can see both in the results).

var body=document.body,
    parent=body.querySelector(".table"),
    rows=parent.querySelectorAll(".row"),
    table=document.createElement("table"),
    tbody=document.createElement("tbody"),
    row=document.createElement("tr"),
    cell=document.createElement("td"),
    x=rows.length,
    cells=rows[0].querySelectorAll(".column"),
    y=cells.length,
    i,j;
table.appendChild(tbody)
for(i=0;i<x;i++){
    row=row.cloneNode(0);
    cells=rows[i].querySelectorAll(".column");
    y=cells.length;
    for(j=0;j<y;j++){
        cell=cell.cloneNode(0);
        cell.innerHTML=cells[j].innerHTML;
        row.appendChild(cell);
    }
    tbody.appendChild(row);
}
body.appendChild(table);
//body.removeChild(parent);
table{
    color:#f00;
}
.table{display:table;}
.row{display:table-row;}
.column{display:table-cell;}
<div class="table">
    <div class="row">
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
    </div>
    <div class="row">
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
    </div>
    <div class="row">
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
        <div class="column">Info</div>
    </div>
</div>

answered Aug 10, 2016 at 17:04

Shaggy's user avatar

ShaggyShaggy

6,6562 gold badges26 silver badges45 bronze badges

To quickly format this as a table, use this CSS:

div { display: table; }
div.row { display: table-row; }
div.column { display: table-cell; }

From there, you can style it however you need, or it should be copyable to Excel.

If you want to change the markup into a table, it’s pretty easy. You’d just replace the outer div with a table tag, the <div class="row"> elements with tr and the columns with td. Example follows.

<table> <!-- was <div> -->
    <tr> <!-- was <div class="row"> -->
        <td> <!-- was <div class="column"> -->Info</td><!-- was </div> -->
        ...
    </tr> <!-- was </div> -->
</table> <!-- was </div> -->

answered Aug 10, 2016 at 16:57

Jeremy Klukan's user avatar

I actually had to deal with this exact problem recently. The data in these divs is being populated from query results, I would suggest running another foreach loop this time properly inserting them in table cells. You could always set this table to display:none; if you dont want to display duplicates. Alternatively, I would set data-attributes to these divs such as data-row=»1″, data-column=»2″ etc., then manipulate them with javascript and inject them into a table. Once you have your desired data structure you can use this plugin to easily export the results to a CSV file.

answered Aug 10, 2016 at 16:52

Denis Kumbaradzi's user avatar

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Any HTML table that you have created can be converted into an Excel Spreadsheet by using jQuery and it is compatible with all browsers. There are two simple approaches that require basic HTML and jQuery knowledge to achieve this.

    • Approach 1: Using jQuery plugin: A simple jQuery plugin ‘table2excel’ can be used for converting an HTML table to an excel sheet. 

    Syntax:

    $("#table-id").table2excel({
        filename: "excel_sheet-name.xls"
    });
    • Example: 

    html

    <table id="studtable">

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Age</th>

            <th>Address</th>

        </tr>

        <tr>

            <td>101</td>

            <td>Alex</td>

            <td>15</td>

            <td>Maldives</td>

        </tr>

        <tr>

            <td>102</td>

            <td>Chris</td>

            <td>14</td>

            <td>Canada</td>

        </tr>

        <tr>

            <td>103</td>

            <td>Jay</td>

            <td>15</td>

            <td>Toronto</td>

        </tr>

    </table>

    <script>

     $(document).ready(function () {

        $("#studtable").table2excel({

            filename: "Students.xls"

        });

     });

    </script>

    • Output:
     
    ID    Name    Age    Address
    101    Alex    15    Maldives
    102    Chris    14    Canada
    103    Jay    15    Toronto
    • The above output gets converted into an Excel spreadsheet in the exact same manner the HTML table is. About ‘table2excel’: The ‘table2excel’ is a simple yet useful jQuery plugin that allows for exporting HTML table data to an Excel file. The ‘table2excel’ also has a feature to exclude cells that contain a specified class. Syntax for noExport:
    $(document).ready(function() {
        $("#table-id").table2excel({
            exclude: ".noExport",
            filename: "name-of-the-file",
        });
    });
    • Example code for excluding some specified cells: 

    html

    <script src=

    "//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">

    </script>

    <script src=

    "//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">

    </script>

    <button>Export</button>

    <table>

        <thead>

            <tr>

                <td class="noExport">

                    This cell will not be exported.

                </td>

                <td>

                    This cell will get exported.

                </td>

            </tr>

        </thead>

        <tbody>

            <tr>

                <td>Alex</td>

                <td class="noExport">Maldives</td>

            </tr>

            <tr>

                <td>Chris</td>

                <td>Canada</td>

            </tr>

        </tbody>

    </table>

    • Note: In the above sample code, the class ‘.noExport’ has been used to exclude those specified cells from the HTML table data. Therefore the exported Excel Spreadsheet also does not include those cells from the HTML table data.
    • Approach 2: Using simple HTML: Consider the same students table above to understand the below. Let’s use a button in our code which when clicked to converts the HTML data table into an Excel spreadsheet. Note that the ‘export’ button below does not actually convert the HTML table to an excel sheet. This has to used in a proper and already existing HTML code to get the Excel spreadsheet and will not work in this IDE. 

    html

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            HTML Table To Excel

            spreadsheet using

            HTML only

        </title>

    </head>

    <body>

        <table id="studtable">

            <tr>

                <th>ID</th>

                <th>Name</th>

                <th>Age</th>

                <th>Address</th>

            </tr>

            <tr>

                <td>101</td>

                <td>Alex</td>

                <td>15</td>

                <td>Maldives</td>

            </tr>

            <tr>

                <td>102</td>

                <td>Chris</td>

                <td>14</td>

                <td>Canada</td>

            </tr>

            <tr>

                <td>103</td>

                <td>Jay</td>

                <td>15</td>

                <td>Toronto</td>

            </tr>

        </table>

        <button onclick="tableToExcel(

            'studtable', 'Students')">

            Click to Export

        </button>

    </body>

    </html>

    • Output:

     

    HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps. jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more“. 

    • HTML Tutorial and HTML Examples.
    • jQuery Tutorial and jQuery Examples.

    Like Article

    Save Article

    • Remove From My Forums
    • Question

    • User-848409960 posted

      I want to export a div into excel..

      What are the possible solutions..

    Answers

      • Marked as answer by

        Thursday, October 7, 2021 12:00 AM

    • User260886948 posted

      Hi,

      For how to export a div into excel, I find a good example with the following code: http://nice-tutorials.blogspot.com/2010/04/export-div-data-to-excel-in-aspnet.html .

      .Aspx:

      <form id="form1" runat="server">  
      <div id="divExport" runat="server">  
      <table width="500" border="1" cellspacing="0" cellpadding="0">  
      <tr>  
      <td align="left" valign="top" bgcolor="#FFECF5"><strong>id</strong></td>  
      <td align="left" valign="top" bgcolor="#FFECF5"><strong>Name</strong></td>  
      <td align="left" valign="top" bgcolor="#FFECF5"><strong>Birth Date</strong></td>  
      <td align="left" valign="top" bgcolor="#FFECF5"><strong>Gender</strong></td>  
      </tr>  
      <tr>  
      <td align="left" valign="top">1</td>  
      <td align="left" valign="top">Haris Fakhar</td>  
      <td align="left" valign="top">15/10/1984</td>  
      <td align="left" valign="top">male  
      </td>  
      </tr>  
      <tr>  
      <td align="left" valign="top">2</td>  
      <td align="left" valign="top">Omer Fakhar</td>  
      <td align="left" valign="top">01/09/1986</td>  
      <td align="left" valign="top">male</td>  
      </tr>  
      </table>  
      </div>  
      </form>  
      <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Export to Excel" />

      .cs:

      using System;  
      using System.Collections.Generic;  
      using System.Web;  
      using System.Web.UI;  
      using System.Web.UI.WebControls;  
      using System.Net;  
      using System.IO;//Donot forget to import this namespace  
        
      protected void Button1_Click(object sender, EventArgs e)  
      {  
      Response.Clear();  
      Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");  
      Response.Charset = "";  
      Response.ContentType = "application/vnd.xls";  
      System.IO.StringWriter stringWrite = new System.IO.StringWriter();  
      System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);  
      divExport.RenderControl(htmlWrite);  
      Response.Write(stringWrite.ToString());  
      Response.End();  
      } 

      Hope it can help you.

      • Marked as answer by
        Anonymous
        Thursday, October 7, 2021 12:00 AM

    В IE динамически созданный тег привязки должен быть добавлен в DOM для выполнения события click. Кроме того, атрибут загрузки не поддерживается в IE:

    Загрузить атрибут тега A, который не работает в IE

    Редактировать:

    Недавно я опубликовал много ответов на эту проблему, вот два из них:

    изображение не загружается с его собственным расширением

    JS Base64 для загружаемого pdf — Edge

    В основном вы должны использовать msSaveOrOpenBlob() в IE:

    var tF = 'Whatever.xls';
    var tB = new Blob(..);
    
    if(window.top.navigator.msSaveOrOpenBlob){
        //Store Blob in IE
        window.top.navigator.msSaveOrOpenBlob(tB, tF)
    }
    else{
        //Store Blob in others
        var tA = document.body.appendChild(document.createElement('a'));
        tA.href = URL.createObjectURL(tB);
        tA.download = tF;
        tA.style.display = 'none';
        tA.click();
        tA.parentNode.removeChild(tA)
    }
    

    В приведенном выше случае:

    var tT = new XMLSerializer().serializeToString(document.querySelector('table')); //Serialised table
    var tF = 'Whatever.xls'; //Filename
    var tB = new Blob([tT]); //Blob
    
    if(window.top.navigator.msSaveOrOpenBlob){
        //Store Blob in IE
        window.top.navigator.msSaveOrOpenBlob(tB, tF)
    }
    else{
        //Store Blob in others
        var tA = document.body.appendChild(document.createElement('a'));
        tA.href = URL.createObjectURL(tB);
        tA.download = tF;
        tA.style.display = 'none';
        tA.click();
        tA.parentNode.removeChild(tA)
    }
    

    https://jsfiddle.net/23ao1v0s/1/

    Понравилась статья? Поделить с друзьями:
  • Div table word wrap
  • Div style word spacing
  • Div style word break
  • Div not word wrapping
  • Div do not word wrap