Here is a working example for you:
1. Excel Helper class - used to simplify code in your project (namespace excluded):
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
public class ExcelHelper
{
public ExcelHelper(string path)
{
_path = path;
_workbook = _excel.Workbooks.Open(path);
}
private readonly string _path;
private readonly _Application _excel = new _Excel.Application();
private readonly Workbook _workbook;
public IEnumerable<Worksheet> Worksheets()
{
foreach (Worksheet worksheet in _workbook.Worksheets.Cast<Worksheet>())
yield return worksheet;
}
public IEnumerable<Chart> GetCharts(Worksheet worksheet)
{
foreach (var chartObject in worksheet.ChartObjects())
yield return chartObject.Chart;
}
}
Here is a sample Console app showing how to use it:
static class Program
{
static void Main()
{
string path = Path.Combine(Path.Combine(Environment.CurrentDirectory, "Workbooks"), "Book1.xlsx");
ExcelHelper excelHelper = new ExcelHelper(path);
foreach (Worksheet worksheet in excelHelper.Worksheets())
{
Console.WriteLine($"Name: {worksheet.Name}");
if(worksheet.Name.Equals("MySheet"))
{
foreach (Chart chart in excelHelper.GetCharts(worksheet))
{
Console.WriteLine($" - Chart Name: {chart.Name}");
}
}
}
}
}
And finally, the output:
Name: Sheet1
Name: Sheet2
Name: MySheet
- Chart Name: MySheet Chart 1
- Chart Name: MySheet Chart 2
- Chart Name: MySheet MyChart
You can see that the workbook has 3 sheets, one with a custom name. The worksheet with the custom name has 3 charts, the 3rd with a custom name.
The
ExcelHelper
class is far from complete and is only a working example for you to work with.
Hope this points you in the right direction...