簡體   English   中英

使用 JavaScript 將 HTML 表格數據導出到 Excel

[英]Export HTML Table Data to Excel using JavaScript

我試圖按照參考: 使用 JavaScript 將 HTML 導出到 Excel 它適用於我的數據的前三列。 但是最后兩列(我使用嵌套 axios 查找更多數據)不起作用。 我不確定嵌套的 axios是否可能是問題所在。

  • 在我的本地測試中,我可以看到整個數據(或者當我console.log("tableSelect") ,我仍然可以看到整個數據
  • 我導出到excel后,只能看到前三列數據,其余兩列是空白
import Axios from "axios";

window.onload = function (){
const exportExcelBtn = document.getElementById("Export-Excel");

const body = document.getElementsByTagName("body")[0];
const tbl = document.createElement("table");
tbl.setAttribute("border", "2");
tbl.setAttribute("id", "tblId");
const tblbody = document.createElement("tbody");

const getFieldsFromApi = async () => {
    const GetUrl = "abc.net"
    const Doorkey = {username: "token", password: "token"}

    const response = await Axios.get(GetUrl, {auth: Doorkey})
    return response.data.users
}

const getData = async () => {
    const values = await getFieldsFromApi()
    values.forEach(field => {
        const row = document.createElement("tr");
        row.appendChild(addCell(field.name));
        row.appendChild(addCell(field.email));
        row.appendChild(addCell(field.role_type));            
        row.appendChild(addCellBrand(field.id));              // when export to excel, this data is not shown 
        row.appendChild(addCellLanguage(field.locale_id));    // when export to excel, this data is not shown         
        tblbody.appendChild(row);
    })
    tbl.appendChild(tblbody);
    body.appendChild(tbl);
    const exportTableToExcel = (tbl, filename = "") => {
        let downloadLink;
        const dataType = 'application/vnd.ms-excel';
        const tableSelect = document.getElementById(tbl);
        let tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
        // Specify file name
        filename = filename?filename+'.xls':'excel_data.xls';          
        // Create download link element
        downloadLink = document.createElement("a");
        document.body.appendChild(downloadLink);

        if(navigator.msSaveOrOpenBlob){
            let blob = new Blob(['\ufeff', tableHTML], {
                type: dataType
            });
            navigator.msSaveOrOpenBlob( blob, filename );
        }else{
            // Create a link to the file
            downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

            // Setting the file name
            downloadLink.download = filename;
                    
            //triggering the function
            downloadLink.click();
        }
                
        };
        exportTableToExcel(tbl.id); //this is export the excel file
};

const addCell = value => {
    const cell = document.createElement("td");
    const cellText = document.createTextNode(value);
    cell.appendChild(cellText);

    return cell
}

const addCellBrand = value => {
    const cell = document.createElement("td");
    const getBrandFromApi = async () => {
        const GetUrl = `abc.net/${value}`
        const Doorkey = {username: "token", password: "token"}
    
        const response = await Axios.get(GetUrl, {auth: Doorkey})
        const getData = response.data.organizations[0].name
        const cellText = document.createTextNode(getData); 
        cell.appendChild(cellText);
    }
    getBrandFromApi();

    return cell
}

const addCellLanguage = value => {
    const cell = document.createElement("td");
    const getLanguageFromApi = async () => {
        const GetUrl = `abc.net/${value}/fieldList`
        const Doorkey = {username: "token", password: "token"}
    
        const response = await Axios.get(GetUrl, {auth: Doorkey})
        const getData = response.data.locale.presentation_name
        const cellText = document.createTextNode(getData); 
        cell.appendChild(cellText);     
    }
    getLanguageFromApi();

    return cell
}

exportExcelBtn.addEventListener("click", getData);
}

請有人幫忙看看可能是什么問題? 提前致謝

問題在於addCellBrandaddCellLanguage函數。 它們是異步的,您需要在最后等待return cell ,但是在addCell函數中,您嘗試執行同步操作並正確返回函數塊末尾的cell

因此,您需要正確執行異步操作:

addCellBrandaddCellLanguage函數中(它們是相似的,addCellLanguage 也是如此):

const addCellBrand = (value) => {
    const cell = document.createElement("td");
    return new Promise((resolve, reject) => {
      const getBrandFromApi = async () => {
        const GetUrl = `abc.net/${value}`;
        const Doorkey = { username: "token", password: "token" };

        try {
          const response = await Axios.get(GetUrl, {auth: Doorkey});
          const getData = response.data.organizations[0].name
          const cellText = document.createTextNode(getData);
          cell.appendChild(cellText);
          resolve(cell); // here for returning your cell after all
        } catch (err) {
          reject(cell);  // don't forgot about the failure case on your API call
        }
      };
      getBrandFromApi();
    });
  };

現在,您實現了一個異步函數,通過創建一個新的 Promise 來正確地獲取cell

是時候在getData使用這個異步方法了:

const values = await getFieldsFromApi()
values.forEach(async (field) => {
    const cellBrand = await addCellBrand(field.id) 
    const cellLanguage = await addCellLangugae(field.local_id)

    const row = document.createElement("tr");
    row.appendChild(addCell(field.name));
    row.appendChild(addCell(field.email));
    row.appendChild(addCell(field.role_type));            
    row.appendChild(cellBrand);
    row.appendChild(cellLanguage);         
    tblbody.appendChild(row);
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM