-
Notifications
You must be signed in to change notification settings - Fork 0
/
cart-to-xls.php
80 lines (67 loc) · 3.19 KB
/
cart-to-xls.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
add_action('woocommerce_after_cart_totals', 'cart2excel');
function cart2excel()
{
echo '<button id="cartDownload" class="button alt">Download as Excel</button>';
$excelList = array("Product Name", "SKU", "Price", "Quantity", "Subtotal"); // Excel header
foreach (WC()->cart->get_cart() as $cart_item) {
$product = $cart_item['data']; // Products Objects
$regular_price = $product->get_regular_price(); // Normal Price
$sale_price = $product->get_sale_price(); // Sale Price
$price = $product->get_price(); // Last Price
$sku = $product->get_sku(); // Stock Code
$name = $product->get_name(); // Product Name
$quantity = $cart_item['quantity']; // Cart Item Quantity
$line_subtotal = $cart_item['line_subtotal']; // Cart Item Subtotal
array_push($excelList, $name, $sku, $price, $quantity, $line_subtotal); // Add cart items to $excelList array
}
$arr = array_chunk($excelList, 5); // convert one-dimensional array to two-dimensional array php
$jsArray = json_encode($arr); // convert array to json
?>
<script>
// Example data given in question text
var data = <?= $jsArray ?>;
// Building the excel from the Data two-dimensional array
// Each column is separated by ";" and new line "\n" for next row
var excelContent = '';
data.forEach(function (infoArray, index) {
dataString = infoArray.join(';'); // for excel
excelContent += index < data.length ? dataString + '\r\n' : dataString; // for excel
});
// The download function takes a excel string, the filename and mimeType as parameters
// Scroll/look down at the bottom of this snippet to see how download is called
var download = function (content, fileName, mimeType) {
var a = document.createElement('a');
mimeType = mimeType || 'application/octet-stream';
if (navigator.msSaveBlob) {
// IE10
navigator.msSaveBlob(
new Blob(["\uFEFF"+content], {
type: mimeType,
}),
fileName,
);
} else if (URL && 'download' in a) {
//html5 A[download]
a.href = URL.createObjectURL(
new Blob(["\uFEFF"+content], {
type: mimeType,
}),
);
a.setAttribute('download', fileName);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
} else {
location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
}
};
//download button click
const downloadClick = document.getElementById('cartDownload');
downloadClick.addEventListener('click', () => {
// modern excel -> application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
download(excelContent, 'cart-dowload.xls', 'application/vnd.ms-excel;encoding:utf-8'); // for excel
}, false);
</script>
<?php
}