简体   繁体   中英

Name Excel Worksheet using Array C#

I'm trying to name create a new excel worksheet and have the variable name come from an array. Code...

Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Worksheet newWorksheet;
string[] Numbers = new string[12] { "1","2","3","4","5","6","7","8","9","10","11","12"};
string[] Months = new string[12] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
            for (int i = 0; i < Months.Length; i++)
            {
                newWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)xlApp.Worksheets.Add();
                Microsoft.Office.Interop.Excel.Worksheet Numbers[i] = (Worksheet)xlApp.Worksheets["Sheet" + i];
                Numbers[i].Name = Months[i];
            }

I am trying to have the variable name of the new worksheet be the number from the array "Numbers". I get an error when trying since it thinks I am trying to declare an array. Is there any way to do this?

Thanks.

Your code is a bit confusing. You are using the name Month for two different arrays

string[] Months 

and

Microsoft.Office.Interop.Excel.Worksheet Months[i] 

Ending up with this very confusing code

Months[i].Name = Months[i];

Rename one of your arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM