使用 C# 在 Excel 电子表格中创建图表

博客类别:成像办公.NET

2024/05/08

Microsoft Office Excel 是一款电子表格应用程序,允许您编辑电子表格数据并使用图表可视化电子表格数据。Excel 支持以下图表类型:柱形图、折线图、饼图、条形图、面积图、XY(散点图)、地图、股票图、曲面图、雷达图、树状图、旭日图、直方图、箱线图、瀑布图、漏斗图、组合图。

VintaSoft Imaging .NET SDK + VintaSoft Office .NET Plug-in 提供强大的 .NET API,用于处理存储在 XLSX 文件中的电子表格。
VintaSoft Imaging .NET SDK 允许创建以下类型的 Excel 图表:

要使用 VintaSoft Imaging .NET SDK 在 Excel 电子表格中创建图表,您应该完成以下步骤:

以下 C# 代码演示了如何将"标准"图表添加到 Excel 表格:
public static void AddStandardChartToXlsxWorksheet(string outXlsxFilename)
{
    // create a spreadsheet editor for synchronous editing of new spreadsheet document
    using (SpreadsheetEditor editor = SpreadsheetEditor.CreateEditor())
    {
        // get the first worksheet (empty)
        Worksheet sheet = editor.Document.Worksheets[0];
        
        // start the worksheet editing
        WorksheetEditor worksheetEditor = editor.StartEditing(sheet);

        // set worksheet name
        worksheetEditor.SetName("Example of add chart");
        
        // set categories and series for chart
        editor.SetCellValue(sheet, "A2", "Series 1");
        editor.SetCellValue(sheet, "A3", "Series 2");
        editor.SetCellValue(sheet, "A4", "Series 3");
        editor.SetCellValue(sheet, "B1", "Category 1");
        editor.SetCellValue(sheet, "C1", "Category 2");
        editor.SetCellValue(sheet, "D1", "Category 3");
        editor.SetCellValue(sheet, "E1", "Category 4");

        // set sample values for chart
        editor.SetCellValue(sheet, "B2", 5);
        editor.SetCellValue(sheet, "C2", 15);
        editor.SetCellValue(sheet, "D2", 45.5);
        editor.SetCellValue(sheet, "E2", 35);
        editor.SetCellValue(sheet, "B3", 110);
        editor.SetCellValue(sheet, "C3", 90);
        editor.SetCellValue(sheet, "D3", 88);
        editor.SetCellValue(sheet, "E3", 25);
        editor.SetCellValue(sheet, "B4", 15);
        editor.SetCellValue(sheet, "C4", 50);
        editor.SetCellValue(sheet, "D4", 20);
        editor.SetCellValue(sheet, "E4", 45);

        // add new Line chart to the worksheet
        SheetDrawing chart = editor.AddChart(sheet, StandardChartType.Line_LineWithMarkers_Horizontal, "A1:E4", new SheetDrawingLocation("A7:F17"));
        // set the chart title
        worksheetEditor.CreateChartPropertiesEditor(chart).SetTitle("Line Chart Example (Horizontal)");

        // finish the spreadsheet editing
        editor.FinishEditing();

        // save created spreadsheet document to a XLSX file
        editor.SaveAs(outXlsxFilename);
    }
}