ExpressJS:使用 Express 返回 .txt 请求/下载 xlsx 文件

发布于 2025-01-20 05:28:34 字数 2093 浏览 0 评论 0原文

我的服务器端使用 Express JS

const XLSX = require('xlsx');

module.exports = () => {
  return async (req, res, next) => {
    try {
      
      const data = [['1', '2', '3'],['4', '5', '6']];

      const filename = `Testing.xlsx`;

      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.aoa_to_sheet(data);
      const merge = [
        { s: { r: 0, c: 0 }, e: { r: 0, c: 9 } },
        { s: { r: 1, c: 1 }, e: { r: 1, c: 7 } },
        { s: { r: 2, c: 1 }, e: { r: 2, c: 7 } },
        { s: { r: 2, c: 8 }, e: { r: 3, c: 9 } },
        { s: { r: 3, c: 0 }, e: { r: 4, c: 0 } },
        { s: { r: 3, c: 1 }, e: { r: 4, c: 1 } }
      ];
      ws['!merges'] = merge;
      XLSX.utils.book_append_sheet(wb, ws, 'Detail');
      const wbBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

      res.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8');
      res.attachment(filename);
      return res.status(200).send(wbBuffer);
    } catch (error) {
      logger.log('error', 'DownloadSellerFinancialAccounts', { error });
      return next(error);
    }
  };
};

同时在客户端站点

export function apiDownloadFinancilJournal() {
  return axios.get(`${paymentUrlApi.downloadFinancialJournal}`, { responseType: 'blob' });
}



apiDownloadFinancilJournal()
  .then((res) => {
    const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' }));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `Financial-Journal.xlsx`);
    document.body.appendChild(link);
    link.click();
  })
  .catch((err) => {
    this.setState({ errorMessage: err.response?.data?.message ?? 'Server Error' });
  });
};

我的问题是,我哪一方面做错了?因为结果是txt而不是xlsx文件。我尝试过不同类型的流数据(blob、arrayBuffer、buffer),但结果更糟

My server side using Express JS

const XLSX = require('xlsx');

module.exports = () => {
  return async (req, res, next) => {
    try {
      
      const data = [['1', '2', '3'],['4', '5', '6']];

      const filename = `Testing.xlsx`;

      const wb = XLSX.utils.book_new();
      const ws = XLSX.utils.aoa_to_sheet(data);
      const merge = [
        { s: { r: 0, c: 0 }, e: { r: 0, c: 9 } },
        { s: { r: 1, c: 1 }, e: { r: 1, c: 7 } },
        { s: { r: 2, c: 1 }, e: { r: 2, c: 7 } },
        { s: { r: 2, c: 8 }, e: { r: 3, c: 9 } },
        { s: { r: 3, c: 0 }, e: { r: 4, c: 0 } },
        { s: { r: 3, c: 1 }, e: { r: 4, c: 1 } }
      ];
      ws['!merges'] = merge;
      XLSX.utils.book_append_sheet(wb, ws, 'Detail');
      const wbBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });

      res.header('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8');
      res.attachment(filename);
      return res.status(200).send(wbBuffer);
    } catch (error) {
      logger.log('error', 'DownloadSellerFinancialAccounts', { error });
      return next(error);
    }
  };
};

Meanwhile in the client site

export function apiDownloadFinancilJournal() {
  return axios.get(`${paymentUrlApi.downloadFinancialJournal}`, { responseType: 'blob' });
}



apiDownloadFinancilJournal()
  .then((res) => {
    const url = window.URL.createObjectURL(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' }));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', `Financial-Journal.xlsx`);
    document.body.appendChild(link);
    link.click();
  })
  .catch((err) => {
    this.setState({ errorMessage: err.response?.data?.message ?? 'Server Error' });
  });
};

My question is, in which side I did it wrong? because the result is a txt instead of xlsx file. I have tried different type of stream data (blob, arrayBuffer, buffer) but the result is even worse

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文