C# 使用 EPPlus 库操作 Excel 文件:添加图表
EPPlus 是一个用于操作 Excel 文件的开源库,它允许您创建、修改和读取 Excel 文件。本文将介绍如何使用 EPPlus 添加图表。
- 引入 EPPlus 库
首先,在 Visual Studio 中创建一个新的 C# 项目,然后右键点击项目,选择“管理 NuGet 程序包”,在搜索框中搜索“EPPlus”,并安装最新版本的 EPPlus 库。
- 创建 Excel 文件
接下来,我们需要使用 EPPlus 创建一个 Excel 文件。在代码中,我们需要引入以下命名空间:
using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
然后,可以使用以下代码创建一个新的 Excel 文件:
ExcelPackage excelPackage = new ExcelPackage();
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
- 添加数据和图表
接下来,我们需要向 Excel 文件添加数据,并添加图表。在代码中,我们可以使用以下代码添加数据:
worksheet.Cells['A1'].Value = "Month";
worksheet.Cells['B1'].Value = "Sales";
worksheet.Cells['A2'].Value = "January";
worksheet.Cells['B2'].Value = 100;
worksheet.Cells['A3'].Value = "February";
worksheet.Cells['B3'].Value = 120;
worksheet.Cells['A4'].Value = "March";
worksheet.Cells['B4'].Value = 90;
然后,我们可以使用以下代码创建一个柱形图:
ExcelChart chart = worksheet.Drawings.AddChart("Chart1", eChartType.ColumnClustered) as ExcelChart;
chart.SetPosition(0, 0, 0, 0);
chart.SetSize(600, 400);
chart.Title.Text = "Sales by Month";
chart.Series.Add(worksheet.Cells['B2:B4'], worksheet.Cells['A2:A4']);
- 保存 Excel 文件
最后,我们需要将 Excel 文件保存到本地磁盘。可以使用以下代码完成此操作:
excelPackage.SaveAs(new FileInfo(@"C:\Users\username\Desktop\sales.xlsx"));
完整代码如下:
using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
using System.IO;
namespace ExcelChartExample
{
class Program
{
static void Main(string[] args)
{
ExcelPackage excelPackage = new ExcelPackage();
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells['A1'].Value = "Month";
worksheet.Cells['B1'].Value = "Sales";
worksheet.Cells['A2'].Value = "January";
worksheet.Cells['B2'].Value = 100;
worksheet.Cells['A3'].Value = "February";
worksheet.Cells['B3'].Value = 120;
worksheet.Cells['A4'].Value = "March";
worksheet.Cells['B4'].Value = 90;
ExcelChart chart = worksheet.Drawings.AddChart("Chart1", eChartType.ColumnClustered) as ExcelChart;
chart.SetPosition(0, 0, 0, 0);
chart.SetSize(600, 400);
chart.Title.Text = "Sales by Month";
chart.Series.Add(worksheet.Cells['B2:B4'], worksheet.Cells['A2:A4']);
excelPackage.SaveAs(new FileInfo(@"C:\Users\username\Desktop\sales.xlsx"));
}
}
}
原文地址: https://www.cveoy.top/t/topic/oLnO 著作权归作者所有。请勿转载和采集!