Skip to content

Commit

Permalink
feat: add download file as csv button
Browse files Browse the repository at this point in the history
  • Loading branch information
trinhvanminh committed Aug 16, 2024
1 parent f2a3cf7 commit 470345e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
11 changes: 8 additions & 3 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,14 @@
<canvas id="compounding-interest-chart"></canvas>
</section>
<div id="legend-container"></div>
<button id="download-chart">
<i class="fas fa-download"></i> Tải biểu đồ
</button>
<div class="button-group">
<button id="download-chart">
<i class="fas fa-download"></i> Tải biểu đồ
</button>
<button id="download-data">
<i class="fa-solid fa-file-arrow-down"></i> Tải dữ liệu
</button>
</div>
</div>
<section>
<h2>Lãi suất</h2>
Expand Down
37 changes: 35 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,14 @@ const interestRateInput = document.getElementById(
"interest-rate"
) as HTMLInputElement;

const downloadButton = document.getElementById(
const downloadChartButton = document.getElementById(
"download-chart"
) as HTMLButtonElement;

const downloadDataButton = document.getElementById(
"download-data"
) as HTMLButtonElement;

let initialInvestment: number = parseFloat(initInvestmentElm.value);
let lengthOfTimeInMonths: number = parseFloat(lengthOfTimeInYearElm.value) * 12;
let interestRates: InterestRate[] = [...OCB_INTEREST_RATES];
Expand Down Expand Up @@ -127,7 +131,7 @@ addDatasetBtn.addEventListener("click", () => {
updateChart();
});

downloadButton.addEventListener("click", () => {
downloadChartButton.addEventListener("click", () => {
const datasets = getDatasets();
console.log("datasets", datasets);
fullSizeChart.data.datasets = datasets;
Expand All @@ -142,6 +146,35 @@ downloadButton.addEventListener("click", () => {
link.click();
});

downloadDataButton.addEventListener("click", () => {
const data = chart.data.datasets.map((dataset) => {
const { label, data } = dataset;
const formattedData = data.map((item) => {
if (item === null || item === undefined) return 0;

return (item as number).toFixed(2);
});
return [label, ...formattedData];
});

const header = ["Kỳ hạn (lãi suất)", ...(chart.data.labels as string[])];
const rows = [header, ...data];

let csvContent =
"data:text/csv; charset=utf-8," + rows.map((e) => e.join(",")).join("\n");
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");

link.href = encodedUri;

const init = numeral(initialInvestment).format();
const years = numeral(lengthOfTimeInMonths / 12).format("0,0.00");

link.download = `lai-suat_${init}vnd_${years}nam.csv`;

link.click();
});

removeDatasetsBtn.addEventListener("click", () => {
interestRates = [];
renderInterestRateList();
Expand Down

0 comments on commit 470345e

Please sign in to comment.