在Javascript中以正确的格式导出HTML表格

时间:2014-09-23 07:21:36

标签: javascript html-table export-to-excel

我有一张桌子,我有一个数量列。我想用正确的数字格式导出表格,因为当我导出我的表格时,我只得到100而不是100.00。

我的表格如下:

ID    Code    Amount    Time
1      1      100.00    2014-09-22 18:59:25
1      1      100.60    2014-09-22 18:59:25
1      1      100.00    2014-09-22 18:59:25
1      1       12.50    2014-09-22 18:59:25

Excel输出如下:

ID    Code    Amount    Time
1      1         100    2014-09-22 18:59:25
1      1      100.60    2014-09-22 18:59:25
1      1         100    2014-09-22 18:59:25
1      1        12.5    2014-09-22 18:59:25

这是我的代码:

    <script>
    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"><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>{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, filename) {
            if (!table.nodeType) table = document.getElementById(table)
            var ctx = {
                worksheet: name || 'Worksheet',
                table: table.innerHTML
            }

            document.getElementById("dlink").href = uri + base64(format(template, ctx));
            document.getElementById("dlink").download = filename;
            document.getElementById("dlink").click();

        }
    })()
    function download(){
        $(document).find('tfoot').remove();
        var name = document.getElementById("name").innerHTML;
        tableToExcel('table2', 'Sheet 1', name+'.xls')
        setTimeout("window.location.reload()",0.0000001);

    }
    var btn = document.getElementById("btn");
    btn.addEventListener("click",download);
    </script>

有没有办法实现这个目标?我希望我的Excel文件看起来与我表格中的数据完全一样。

2 个答案:

答案 0 :(得分:8)

尝试

<td style='mso-number-format:"#,##0.00"'>100.00</td>

表格HTML。

请参阅小提琴:http://jsfiddle.net/ad3xda1z/1/

问候

阿克塞尔

答案 1 :(得分:0)

excel本身:
默认情况下,它不显示.00 - 但您可以在格式化选项中更改它

所以最终有一个(xml)选项来指定单元格格式。 那么格式化代码就像0.00

实测值: HTML to Excel: How can tell Excel to treat columns as numbers?
some formating code examples
所以你可以尝试将style="mso-number-format:0\.00000;"添加到单元格

其他选项是尝试强制excel将单元格内容解释为文本 - 为此,您可以尝试使用'

为每个单元格内容添加前缀

我已经构建了一个堆栈代码示例。 相关代码是:

// deep clone of table
//https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode
var temp_table = document.getElementById('table_XXXX').cloneNode(true);
// get all table cells
var table_cells = temp_table.getElementsByTagName('td');
// console.log("table_cells", table_cells);
// modify all table cells
for (var i = 0; i < table_cells.length; i++) { 
    var cell = table_cells[i];
    // console.log("cell", cell);
    // cell.textContent = "'" + cell.textContent;
    cell.setAttribute("style", "mso-number-format:0\.00000;");
}

console.log("temp_table", temp_table);

&#13;
&#13;
var tableToExcel = (function () {
	// var uri = 'data:application/vnd.ms-excel;base64,';
	
	var template = '<html lang="en" xml:lang="en" 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"><meta name="DC.language" content="en"><!--[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>';
	
	// var  base64 = function (s) {
		// return window.btoa(unescape(encodeURIComponent(s)))
	// };
	
	var 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
		}
		// return uri + base64(format(template, ctx));
		return format(template, ctx);
	}
})()


function saveAsFile(link, content, mimetype, filename) {
	// https://developer.mozilla.org/en-US/docs/Web/API/Blob
	// var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
	// var oMyBlob = new Blob(aFileParts, {type: 'text/html'}); // the blob
	
	// https://stackoverflow.com/a/16330385/574981
	var blob = new Blob([content], mimetype);
	var url  = URL.createObjectURL(blob);
	
	console.log("update download link:");
	var a = link;
	a.download    = filename;
	a.href        = url;
	// a.textContent = "Download File";
	console.log("download link:", a);
}

function saveAsFile_handleClick(event){
	console.log("saveAsFile_handleClick");
	// deep clone of table
	//https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode
	var temp_table = document.getElementById('table_XXXX').cloneNode(true);
	// get all table cells
	var table_cells = temp_table.getElementsByTagName('td');
	// console.log("table_cells", table_cells);
	// modify all table cells
	for (var i = 0; i < table_cells.length; i++) { 
		var cell = table_cells[i];
		// console.log("cell", cell);
		// cell.textContent = "'" + cell.textContent;
		cell.setAttribute("style", "mso-number-format:0\.000;");
	}
	console.log("temp_table", temp_table);
	// function saveAsFile(link, content, mimetype, filename);
	saveAsFile(
		this,
		tableToExcel(temp_table, 'Sheet 1'), 
		{type: "application/msexcel"}, 
		"test.xls"
	);
} 

function initSystem(){
	console.groupCollapsed("system init:");
	
	// save output button
	var saveOutputButton = document.getElementById("saveAsFile");
	if (saveOutputButton) {
		console.log("add click event to '#saveAsFile':");
		saveOutputButton.addEventListener('click', saveAsFile_handleClick, false);
	}
	
	console.log("finished.");
	console.groupEnd();
}

/* * pure JS - newer browsers...* */
document.addEventListener('DOMContentLoaded', initSystem, false);
&#13;
#btn {
  margin: 1em;
}

tr:hover {
  background-color: rgba(255, 200, 0, 0.5);
  
}

td {
  padding: 0 1.5em;
  text-align: right;
}


a, a:link {
	margin:					0px;
	padding:				0px;
	text-decoration:		none;
	color:					inherit;
	cursor:					pointer;
	display:				inline;
}


a:hover {
	background-color:		rgba(255,190,000,0.5);
	/*box-shadow:			x y color [blur] [spread] [inset]*/
	box-shadow:				0px 0px 5px rgba(255,190,0,0.5), 0px 0px 20px rgba(255,190,0,0.5);
}


.button, a.button:link {
	display:				block;
	width:					20em;
	padding:				0.5em;
	margin:					1em;
	border-radius:			1em;
	background-color:		rgba(0, 0, 0, 0.35);
	box-shadow:				0px 0px 10px rgba(0,0,0,0.2), 0px 0px 10px rgba(255,255,255,0.1) inset;
	cursor:					pointer;
	text-align:				center;
}

.button:hover, a.button:link:hover {
	background-color:		rgba(0, 0, 0, 0.36);
	box-shadow:				1px 1px 10px rgba(0,0,0,0.3), 0px 0px 10px rgba(255,255,255,0.1) inset;
}
&#13;
<div>
	<a class="button" id="saveAsFile" href="#">
		Save Table to Excel File
	</a>
</div>


<div id="tablecontainer">
	<table id="table_XXXX">
		<tbody>
			<tr>
				<th>ID</th>
				<th>Code</th>
				<th>Amount</th>
				<th>Time</th>
			</tr>
			<tr>
				<td>1</td>
				<td>1</td>
				<td>100.00</td>
				<td>2014-09-19 18:59:25</td>
			</tr>
			<tr>
				<td>1</td>
				<td>1</td>
				<td>100.60</td>
				<td>2014-09-20 18:59:25</td>
			</tr>
			<tr>
				<td>1</td>
				<td>1</td>
				<td>200.00</td>
				<td>2014-09-21 18:59:25</td>
			</tr>
			<tr>
				<td>1</td>
				<td>1</td>
				<td>12.50</td>
				<td>2014-09-22 18:59:25</td>
			</tr>
		</tbody>
	</table>
</div>
&#13;
&#13;
&#13;