Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

c# - Trying to add multiple sheets to excel

i'm trying to programmatically add sheets to a new excel document.

my expected output is sheets named 'test1-20' but instead i get 'Sheet1-19, test20'.

why doesn't this work?

Workbook workbook;
Application objExcel;

objExcel = new Application();
objExcel.Visible = false;
objExcel.DisplayAlerts = false;

for (var i = 0; i < worksheets.Count; i++)
{
    workbook= objExcel.Workbooks.Add(Missing.Value);
    var worksheet = (Worksheet)workbook.Worksheets.get_Item(i + 1);
    worksheet.Name = string.Format("test{0}", i + 1);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

using System;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

void MyMethod()
{
    try
    {
        var _excel = new Excel();

        var wb = _excel.Workbooks.Add();
        var collection = new Microsoft.Office.Interop.Excel.Worksheet[20];

        for (var i = 19; i >= 0; i--)
        {
            collection[i] = wb.Worksheets.Add();
            collection[i].Name = String.Format("test{0}", i + 1);
        }

        for (var i = 0; i < 3; i++)
        {
            wb.Worksheets[21].Delete();
        }

        //collection is an array of worksheet objects,
        //the worksheet objects in your workbook.
        //You can access each individual worksheet and
        //work with it in the same way you access any object in an array

        var thisWorksheet = collection[9];
        var thisRange = thisWorksheet.Range["A1"];
        thisRange.Value = "Hello World";

        wb.SaveAs(@"c:estwhatever.xlsx");
        wb.Close();
    }
    finally
    {
        Marshal.ReleaseComObject(_excel);
    }
}

Your visible property is set to false by default, so it is not neccessary to do this explicitly, no alerts are displayed in the above code so this isn't neccessary either. I have tested the above code and can confirm it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...