Excel处理控件Aspose.Cells教程:使用C#在Excel中创建折线图

可视化长期趋势是许多商业报告的核心需求。折线图能够清晰直观地呈现连续轴上的数据序列,因此非常适合展示业绩、销售或任何基于时间的数据。在本指南中,我们将向您展示如何使用Aspose.Cells for .NET和 C# 以编程方式生成折线图。

Aspose.Cells官方试用版免费下载,请联系慧都科技

加入Aspose技术交流QQ群(1041253375),与更多小伙伴一起探讨提升开发技能。

用于创建折线图的 C# Excel 库

Aspose.Cells for .NET是一款功能全面的 API,使开发人员无需 Microsoft Office 即可处理 Excel 文件。它支持创建、编辑和自定义各种类型的图表,包括折线图。主要优势包括:

  • 丰富的 API 接口——完全控制图表类型、系列、坐标轴和格式。
  • 无 COM 依赖项– 可在任何支持 .NET 的平台上运行。
  • 高性能——高效处理大型工作簿。
  • 支持多种格式——读/写 XLSX、XLS、CSV、PDF 等格式。

入门

  1. 从慧都网下载最新的 Aspose.Cells for .NET 。

  2. 通过 NuGet安装: PM> Install-Package Aspose.Cells

  3. Aspose.Cells在你的项目中添加对它的引用。

使用 C# 在 Excel 中创建折线图

以下是两个实际例子:

  1. 简单的单系列折线图——非常适合快速可视化趋势。
  2. 带辅助轴的多系列折线图——在比较不同尺度的数据集时非常有用。

这两个例子都是完整的、可直接编译的 C# 程序。

示例 1 – 简单单系列折线图

// 1. Create a new workbook and obtain the first worksheet.
var workbook = new Workbook();
var sheet = workbook.Worksheets[0];

// ------------------------------------------------------------
// 2. Populate worksheet with sample data.
// ------------------------------------------------------------
//    A          B
// 1  Month    Sales
// 2  Jan       120
// 3  Feb       150
// 4  Mar       180
// 5  Apr       210
// ------------------------------------------------------------
string[] months = { "Jan", "Feb", "Mar", "Apr" };
double[] sales = { 120, 150, 180, 210 };

sheet.Cells["A1"].PutValue("Month");
sheet.Cells["B1"].PutValue("Sales");

for (int i = 0; i < months.Length; i++)
{
    sheet.Cells[i + 1, 0].PutValue(months[i]); // Column A
    sheet.Cells[i + 1, 1].PutValue(sales[i]); // Column B
}

// ------------------------------------------------------------
// 3. Add a Line chart object.
// ------------------------------------------------------------
// Parameters: (type, upper left row, upper left column, lower right row, lower right column)
int chartIndex = sheet.Charts.Add(ChartType.Line, 6, 0, 26, 10);
Chart chart = sheet.Charts[chartIndex];
chart.Title.Text = "Monthly Sales Trend";

// ------------------------------------------------------------
// 4. Add the series ¨C data range refers to the Sales column.
// ------------------------------------------------------------
int seriesIndex = chart.NSeries.Add("=Sheet1!$B$2:$B$5", true);
chart.NSeries[seriesIndex].Name = "Sales";

// ------------------------------------------------------------
// 5. Set category (X?axis) data ¨C months.
// ------------------------------------------------------------
chart.NSeries.CategoryData = "=Sheet1!$A$2:$A$5";

// ------------------------------------------------------------
// 6. Optional: customize axes titles.
// ------------------------------------------------------------
chart.CategoryAxis.Title.Text = "Month";
chart.ValueAxis.Title.Text = "Sales";

// ------------------------------------------------------------
// 7. Save the workbook.
// ------------------------------------------------------------
workbook.Save("SimpleLineChart.xlsx");
Console.WriteLine("Workbook with Line chart saved as SimpleLineChart.xlsx");

解释

  • 工作簿在内存中创建,并填充了月份和销售数据。
  • ChartType.Line创建基本折线图。
  • NSeries.Add定义数据系列;CategoryData分配 X 轴标签。
  • 生成的文件SimpleLineChart.xlsx包含一个格式完整的折线图。

示例 2 – 带辅助坐标轴的多系列折线图

// 1. Initialize workbook and worksheet.
var workbook = new Workbook();
var sheet = workbook.Worksheets[0];

// ------------------------------------------------------------
// 2. Add sample data for two metrics: Revenue (primary) and
//    Profit Margin (secondary).
// ------------------------------------------------------------
//    A          B        C
// 1  Month    Revenue   Profit%
// 2  Jan       3000      12
// 3  Feb       3500      15
// 4  Mar       4000      13
// 5  Apr       3800      14
// ------------------------------------------------------------
string[] months = { "Jan", "Feb", "Mar", "Apr" };
double[] revenue = { 3000, 3500, 4000, 3800 };
double[] profitPct = { 12, 15, 13, 14 };

sheet.Cells["A1"].PutValue("Month");
sheet.Cells["B1"].PutValue("Revenue");
sheet.Cells["C1"].PutValue("Profit%");

for (int i = 0; i < months.Length; i++)
{
    sheet.Cells[i + 1, 0].PutValue(months[i]);      // Month
    sheet.Cells[i + 1, 1].PutValue(revenue[i]);    // Revenue
    sheet.Cells[i + 1, 2].PutValue(profitPct[i]);  // Profit%
}

// ------------------------------------------------------------
// 3. Insert a Line chart.
// ------------------------------------------------------------
int chartIdx = sheet.Charts.Add(ChartType.Line, 7, 0, 27, 12);
Chart chart = sheet.Charts[chartIdx];
chart.Title.Text = "Revenue vs. Profit Margin";
chart.NSeries.CategoryData = "=Sheet1!$A$2:$A$5";

// ------------------------------------------------------------
// 4. Add Revenue series (primary axis).
// ------------------------------------------------------------
int revSeriesIdx = chart.NSeries.Add("=Sheet1!$B$2:$B$5", true);
chart.NSeries[revSeriesIdx].Name = "Revenue";           
chart.NSeries[revSeriesIdx].Type = ChartType.Line; // Explicit, though default

// ------------------------------------------------------------
// 5. Add Profit% series (secondary axis) and set marker style.
// ------------------------------------------------------------
int profitSeriesIdx = chart.NSeries.Add("=Sheet1!$C$2:$C$5", true);
chart.NSeries[profitSeriesIdx].Name = "Profit%";
chart.NSeries[profitSeriesIdx].Type = ChartType.Line;
chart.NSeries[profitSeriesIdx].PlotOnSecondAxis = true; // Use secondary Y?axis

// Optional: customize marker for profit series
chart.NSeries[profitSeriesIdx].Marker.MarkerStyle = ChartMarkerType.Circle;
chart.NSeries[profitSeriesIdx].Marker.MarkerSize = 10;
chart.NSeries[profitSeriesIdx].Marker.Area.ForegroundColor = Color.Orange;

// ------------------------------------------------------------
// 6. Axis titles.
// ------------------------------------------------------------
chart.CategoryAxis.Title.Text = "Month";
chart.ValueAxis.Title.Text = "Revenue (USD)";
chart.SecondValueAxis.Title.Text = "Profit %";

// ------------------------------------------------------------
// 7. Save workbook.
// ------------------------------------------------------------
workbook.Save("MultiSeriesLineChart.xlsx");
Console.WriteLine("Workbook saved as MultiSeriesLineChart.xlsx");

要点

  • 增加了两个系列:收入(主轴)和利润率(次轴),以说明不同的尺度。
  • PlotOnSecondAxis = true将第二组数据移至 Y 轴右侧。
  • 标记自定义使次要系列在视觉上独具特色。
  • 最终文件MultiSeriesLineChart.xlsx包含一个功能齐全的多系列折线图。

结论

使用 Aspose.Cells for .NET 创建折线图既简单又高度可定制。无论您需要快速绘制单系列趋势线,还是需要创建带有辅助坐标轴的复杂多系列图表,该库都可通过直观的 API 提供全面的控制。您可以以提供的代码示例为起点,并根据您的具体报表需求进行调整。

Aspose.Cells官方试用版免费下载,请联系慧都科技

加入Aspose技术交流QQ群(1041253375),与更多小伙伴一起探讨提升开发技能。

posted @ 2025-12-25 11:43  IT开发者笔记  阅读(0)  评论(0)    收藏  举报