You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于SharePoint列表用REST+JS创建动态堆叠条形图求助

Stacked Bar Chart with SharePoint 2013 REST & Chart.js (Dynamic Data)

Hey there! I'll walk you through exactly how to build this dynamic stacked bar chart as someone who's been in your beginner shoes. We'll use Chart.js since it's super approachable and plays nicely with SharePoint 2013.

Step 1: Confirm Your SharePoint List Structure

First, make sure your list columns match this setup (adjust internal names if yours differ):

  • ProjectType: Single line of text (stores values like A, B, C, etc.)
  • 15 number columns for each technology (e.g., Java, Python, SharePoint, .Net, and your other 11 techs)

Step 2: Full Code Implementation

You can drop this into a Script Editor Web Part on any SharePoint page—just swap out the placeholder values with your list details:

<!-- Load Chart.js from CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<!-- Container for the chart -->
<div style="width: 80%; margin: 20px auto;">
  <canvas id="techStackChart"></canvas>
</div>

<script type="text/javascript">
// Replace these with your list name and tech column internal names
const LIST_NAME = "YourProjectList";
const TECH_COLUMNS = ["Java", "Python", "SharePoint", ".Net", "Tech5", "Tech6", "Tech7", "Tech8", "Tech9", "Tech10", "Tech11", "Tech12", "Tech13", "Tech14", "Tech15"];

// Fetch data from SharePoint REST API
async function fetchSharePointData() {
  try {
    // Build the select query for all needed fields
    const selectFields = `ProjectType,${TECH_COLUMNS.join(',')}`;
    const restUrl = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('${LIST_NAME}')/items?$select=${selectFields}`;

    const response = await fetch(restUrl, {
      headers: {
        "Accept": "application/json;odata=verbose"
      }
    });

    if (!response.ok) throw new Error(`Failed to fetch data: ${response.statusText}`);
    
    const data = await response.json();
    return data.d.results;
  } catch (error) {
    console.error("Error fetching SharePoint data:", error);
    alert("Oops! Couldn't load chart data. Check the browser console for details.");
    return [];
  }
}

// Process raw SharePoint data into Chart.js-friendly format
function processChartData(rawItems) {
  // Get unique Project Types (dynamic—auto-includes new ones added to the list)
  const projectTypes = [...new Set(rawItems.map(item => item.ProjectType))];
  
  // Create a dataset for each technology
  const datasets = TECH_COLUMNS.map((tech, index) => {
    // Generate unique, evenly spaced colors for each tech (customize if you want)
    const hue = (index * 24) % 360;
    const color = `hsl(${hue}, 70%, 60%)`;

    return {
      label: tech,
      data: projectTypes.map(type => {
        // Match each project type to its tech count (default to 0 if no entry exists)
        const item = rawItems.find(i => i.ProjectType === type);
        return item ? item[tech] : 0;
      }),
      backgroundColor: color,
      stack: 'Stack 0' // Ensures all datasets stack together on the chart
    };
  });

  return {
    labels: projectTypes,
    datasets: datasets
  };
}

// Initialize and render the chart
async function renderChart() {
  const rawData = await fetchSharePointData();
  if (rawData.length === 0) return;

  const chartData = processChartData(rawData);
  const ctx = document.getElementById('techStackChart').getContext('2d');

  new Chart(ctx, {
    type: 'bar',
    data: chartData,
    options: {
      responsive: true,
      scales: {
        x: {
          stacked: true,
          title: {
            display: true,
            text: 'Project Type'
          }
        },
        y: {
          stacked: true,
          title: {
            display: true,
            text: 'Number of Uses'
          },
          beginAtZero: true // Start Y-axis at 0 for accurate comparisons
        }
      },
      plugins: {
        legend: {
          position: 'top',
        },
        title: {
          display: true,
          text: 'Technology Usage by Project Type'
        }
      }
    }
  });
}

// Run the chart render when the page finishes loading
_spBodyOnLoadFunctionNames.push("renderChart");
</script>

Step 3: Key Customizations for Your Setup

  • List Name: Replace YourProjectList with the exact name of your SharePoint list.
  • Tech Columns: Update the TECH_COLUMNS array with the internal names of your 15 technology columns. To find internal names:
    1. Go to your list settings
    2. Click on a column name
    3. Check the URL—you'll see Field=InternalColumnName (e.g., Field=Java or Field=SharePoint)
  • Colors: The code generates automatic colors, but you can swap the color value with hex codes (like #FF5733) if you want specific shades.

How It Works

  1. Dynamic X-Axis: The projectTypes array pulls unique values from the ProjectType column—any new project types added to the list will automatically appear on the X-axis.
  2. Stacked Data: Each technology gets its own dataset, and the stack: 'Stack 0' property tells Chart.js to stack them all together.
  3. Error Handling: Basic error catching alerts you if data fails to load, and logs details to the browser console for easy debugging.

Deployment Tips

  • Add this code to a Script Editor Web Part (SharePoint 2013 classic) or a Modern Script Editor (if you've enabled modern pages).
  • Test first with a small subset of data to make sure fields are mapped correctly.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:20:17