You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用JavaScript将数据添加至现有Excel工作表?附数据获取代码

How to Add AJAX-Fetched Data to an Existing Excel Worksheet with JavaScript

First, a quick heads-up: Browser-based JavaScript can’t directly edit local files due to security restrictions. Instead, we’ll use the SheetJS (xlsx) library to read an existing Excel file, modify it in memory, and let the user download the updated version. If your Excel file lives on a server, we’ll also cover a server-side approach for that scenario.

Client-Side Approach Using SheetJS

This works if the user has the existing Excel file on their local machine.

Step 1: Include the SheetJS Library

Add this CDN link to your HTML to access the library:

<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

Step 2: Add HTML for File Selection

Let the user pick their existing Excel file and trigger the update:

<input type="file" id="excelFile" accept=".xlsx, .xls">
<button id="addDataBtn">Add API Data to Excel</button>

Step 3: Combine AJAX with SheetJS Modification

Here’s how to integrate your existing AJAX call with SheetJS to update the Excel file:

document.getElementById('addDataBtn').addEventListener('click', function() {
  const fileInput = document.getElementById('excelFile');
  const selectedFile = fileInput.files[0];

  if (!selectedFile) {
    alert('Please select an Excel file first!');
    return;
  }

  // Read the existing Excel file into memory
  const fileReader = new FileReader();
  fileReader.onload = function(e) {
    const arrayBuffer = new Uint8Array(e.target.result);
    const workbook = XLSX.read(arrayBuffer, { type: 'array' });

    // Grab the first worksheet (replace with your sheet name if needed, e.g., 'UserData')
    const targetSheet = workbook.Sheets[workbook.SheetNames[0]];
    // Convert sheet data to JSON for easy manipulation
    const existingRows = XLSX.utils.sheet_to_json(targetSheet);

    // Fetch your API data (using your existing AJAX code)
    $.ajax({
      type: 'GET',
      url: 'http://127.0.0.1:5000/api/v1/profiledatanew',
      dataType: 'json',
      success: function(apiData) {
        // Format the new data to match your Excel sheet's columns
        const newDataRow = {
          ID: apiData.id,
          Name: apiData.name,
          Relationship_Status: apiData.relationship_status,
          Gender: apiData.gender,
          Hometown: apiData.hometown.name,
          // Handle tagged places (join into a single string or split into columns as needed)
          Tagged_Places: apiData.tagged_places.data.map(place => place.name).join(', ')
        };

        // Add the new row to existing data
        existingRows.push(newDataRow);

        // Convert updated JSON back to a worksheet
        const updatedSheet = XLSX.utils.json_to_sheet(existingRows);
        // Replace the old sheet in the workbook
        workbook.Sheets[workbook.SheetNames[0]] = updatedSheet;

        // Generate and download the updated Excel file
        const updatedFileData = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([updatedFileData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
        const downloadUrl = URL.createObjectURL(blob);
        
        const downloadLink = document.createElement('a');
        downloadLink.href = downloadUrl;
        downloadLink.download = 'updated_profile_data.xlsx';
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        URL.revokeObjectURL(downloadUrl);

        alert('Data added successfully! Check your downloads folder.');
      },
      error: function(err) {
        console.error('API fetch failed:', err);
        alert('Could not fetch data from the API.');
      }
    });
  };

  fileReader.readAsArrayBuffer(selectedFile);
});

Key Tips for This Approach:

  • Sheet Name: If your Excel file has multiple sheets, replace workbook.SheetNames[0] with the exact sheet name (e.g., 'ProfileSheet').
  • Column Matching: Ensure the keys in newDataRow exactly match the header names in your Excel sheet—this is how SheetJS maps data to columns.
  • Tagged Places: Adjust how you handle tagged_places based on your sheet’s structure (e.g., add each place as a separate row or column).

Server-Side Approach (For Server-Stored Excel Files)

If the Excel file is hosted on your server, use a server-side script (Node.js example below) to modify it directly:

Step 1: Install SheetJS on Your Server

npm install xlsx express

Step 2: Create a Server Endpoint to Update the File

const express = require('express');
const XLSX = require('xlsx');
const fs = require('fs');
const app = express();

app.get('/api/update-excel-file', (req, res) => {
  // Path to your existing Excel file on the server
  const excelFilePath = './server_profile_data.xlsx';

  try {
    // Read the workbook
    const workbook = XLSX.readFile(excelFilePath);
    const targetSheet = workbook.Sheets[workbook.SheetNames[0]];
    const existingRows = XLSX.utils.sheet_to_json(targetSheet);

    // Fetch your API data (or accept data sent from the client via POST)
    // For this example, we'll simulate API data—replace with your actual fetch logic
    const apiData = { /* your fetched data here */ };
    const newRow = { /* format data to match sheet columns */ };

    // Add new row and update the sheet
    existingRows.push(newRow);
    const updatedSheet = XLSX.utils.json_to_sheet(existingRows);
    workbook.Sheets[workbook.SheetNames[0]] = updatedSheet;

    // Write the updated workbook back to the server file
    XLSX.writeFile(workbook, excelFilePath);

    res.json({ success: true, message: 'Excel file updated successfully' });
  } catch (err) {
    console.error('Update failed:', err);
    res.status(500).json({ success: false, message: 'Could not update Excel file' });
  }
});

app.listen(5000, () => console.log('Server running on port 5000'));

Call this endpoint from your client-side code after fetching the API data to trigger the server-side update.

Important Notes

  • Browser Security: Client-side code can’t modify local files directly—this is a protective measure. Users must select the file and download the updated version.
  • Large Files: For very large Excel files, server-side processing is better to avoid browser performance issues.
  • File Formats: SheetJS supports both .xlsx and .xls, but .xlsx is recommended for better compatibility.

内容的提问来源于stack exchange,提问作者ShyaliC51

火山引擎 最新活动