xlsx预览

发布于:2024-12-19 ⋅ 阅读:(12) ⋅ 点赞:(0)

只预拉第一页的函数

// Excel 文件预览函数
  const previewExcelFile = async (url: string) => {
    try {
      const response = await fetchWithTimeout(url, timeout);
      if (!response.ok) throw new Error('网络响应失败');

      const res = await response.arrayBuffer();
      const workbook = XLSX.read(new Uint8Array(res), { type: 'array' });
      const sheetName = workbook.SheetNames[0]; // 默认读取第一个表
      const sheet = workbook.Sheets[sheetName];
      const html = XLSX.utils.sheet_to_html(sheet);

      const newWin = window.open('', '_blank');
      if (newWin) {
        newWin.document.write(`
          <html>
            <head>
              <title>${fileName}</title>
              <style>
                table { border-collapse: collapse; width: 100%; }
                th, td { border: 1px solid #ddd; padding: 8px; }
                th { background-color: #f4f4f4; text-align: left; }
              </style>
            </head>
            <body>${html}</body>
          </html>
        `);
      }
      return 1; // 表示成功
    } catch (error) {
      console.error('Excel 文件预览失败:', error);
      return 2; // 表示失败
    }
  };

每一页都预览

// Excel 文件预览函数
const previewExcelFile = async (url: string) => {
  try {
    const response = await fetchWithTimeout(url, timeout);
    if (!response.ok) throw new Error('网络响应失败');

    const res = await response.arrayBuffer();
    const workbook = XLSX.read(new Uint8Array(res), { type: 'array' });

    // 遍历所有工作表
    let combinedHtml = '';
    workbook.SheetNames.forEach((sheetName) => {
      const sheet = workbook.Sheets[sheetName];
      const html = XLSX.utils.sheet_to_html(sheet);
      combinedHtml += `<h2>${sheetName}</h2>${html}`;
    });

    // 在新窗口中展示所有工作表内容
    const newWin = window.open('', '_blank');
    if (newWin) {
      newWin.document.write(`
        <html>
          <head>
            <title>${fileName}</title>
            <style>
              table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }
              th, td { border: 1px solid #ddd; padding: 8px; }
              th { background-color: #f4f4f4; text-align: left; }
              h2 { text-align: center; margin: 20px 0; }
            </style>
          </head>
          <body>${combinedHtml}</body>
        </html>
      `);
    }
    return 1; // 表示成功
  } catch (error) {
    console.error('Excel 文件预览失败:', error);
    return 2; // 表示失败
  }
};