日期字符串视为excel的日期类型(导出json数据)

问题描述 投票:0回答:1

我有一个包含动态属性的json对象,想要将其导出到excel,以便excel将日期字符串(2020-03-13)识别为日期对象(我不知道任何json键的类型,所以我不能使用不输入任何格式,日期字符串也可以有时间戳)。 当我使用 xlsx 下载 Excel 时,生成的 Excel 无法将日期字符串识别为 Excel 的日期类型。 如何使用 xlsx 库或不使用 xlsx 库来解决此问题。

我尝试使用xlsx,但没有成功。还尝试首先创建 tsv 字符串,然后使用带有 xlsx 文件 mimetype 的 blob 将其导出为 .xlsx。(但 excel 无法打开它)

json tsv转excel的演示代码

// Sample JSON data
    const jsonData = [
        { "name": "John Doe", "age": 28, "date": "2023-10-08" },
        { "name": "Jane Smith", "age": 32, "date": "2024-03-15" },
        { "name": "Alice Johnson", "age": 45, "date": "2024-01-20" }
    ];

    // Convert JSON to TSV
    function jsonToTsv(jsonData) {
        const headers = Object.keys(jsonData[0]).join("\t");  // Get headers from JSON keys
        const rows = jsonData.map(row => 
            Object.values(row).join("\t") // Join values with tabs
        ).join("\n");  // Join rows with newline

        return `${headers}\n${rows}`;
    }

    // Download the TSV as an Excel file
    function downloadAsExcel(tsvData, fileName) {
        // Create a Blob for the TSV data and specify the MIME type as Excel
        const blob = new Blob([tsvData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

        // Create a URL for the Blob
        const url = URL.createObjectURL(blob);

        // Create a link element
        const link = document.createElement('a');
        link.href = url;
        link.download = fileName; // File name for download

        // Append the link to the document and trigger click
        document.body.appendChild(link);
        link.click();

        // Remove the link element and revoke the object URL
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }

    // Button click event to download JSON as Excel
    document.getElementById('download-btn').addEventListener('click', function () {
        // Convert JSON to TSV format
        const tsvData = jsonToTsv(jsonData);

        // Convert TSV to Excel format and trigger download
        downloadAsExcel(tsvData, "data.xlsx");
    });

使用 xlsx 的演示代码

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Download Excel from JSON</title>

    <!-- Add xlsx script from CDN -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

</head>

<body>

    <button onclick="downloadExcel()">Download Excel</button>

    <script>

        // Sample JSON Data

        const jsonData = [

            { "name": "John Doe", "age": "28", "birthdate": "2023-10-08" },

            { "name": "Jane Smith", "age": "32", "birthdate": "2024-03-15" }

        ];

        // Function to Convert JSON Data to Excel and Trigger Download

        function downloadExcel() {

            // Create a new workbook and worksheet

            const wb = XLSX.utils.book_new();  // Create a new workbook

            const ws = XLSX.utils.json_to_sheet(jsonData);  // Convert JSON to worksheet

            // Append worksheet to workbook

            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // Trigger a download of the Excel file

            XLSX.writeFile(wb, 'data.xlsx');

        }

  

</body>

</html>

reactjs excel date datetime js-xlsx
1个回答
0
投票

“想要将其导出到 Excel,以便 Excel 将日期字符串(2020-03-13)识别为日期对象” - 您的意思是要将 json 文件导入到 Excel 吗?

您可以使用内置选项将 json 文件导入 Power Query。

 [
        { "name": "John Doe", "age": 28, "date": "2023-10-08" },
        { "name": "Jane Smith", "age": 32, "date": "2024-03-15" },
        { "name": "Alice Johnson", "age": 45, "date": "2024-01-20" }
  ]

转到“数据”、“获取数据”、“从文件”、“从 Json”,导航到文件并将其打开。 该文件在 Power Query 中打开:

enter image description here

将其转换为表格,展开列并将所需列的格式设置为日期:

let
    Source = Json.Document(File.Contents("C:\Users\Michal\OneDrive\Documents\test.json")),
    #"Converted to Table" = Table.FromList(Source, Splitter.SplitByNothing(), null, null, ExtraValues.Error),
    #"Expanded Column1" = Table.ExpandRecordColumn(#"Converted to Table", "Column1", {"name", "age", "date"}, {"Column1.name", "Column1.age", "Column1.date"}),
    #"Changed Type" = Table.TransformColumnTypes(#"Expanded Column1",{{"Column1.date", type date}})
in
    #"Changed Type"

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.