Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 90224

How to copy specific sheet name from excel and save it to a new location? Using C#

$
0
0

I am using C# Windows Forms.

Goal:

If I have multiple excel sheets.

For example, "Sheet1, Sheet2, Sheet3, TestSheet1, TestSheet2"

How can I grab specific sheet name e.g. ["Sheet2"] and save it as a new excel workbook?

This is what I have so far:

Button Click:

private void button1_Click(object sender, EventArgs e)
{
    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
    Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open("C:\Users\LV98\Desktop\Test C#\excel_file.xlsx");

    excelBook.Worksheets.Copy("Sheet2");
}

Update:

Here is where I got to.

private void button1_Click(object sender, EventArgs e)
{
    Excel.Application excelApp;

    string fileTarget = "C:\\Users\\LV98\\Desktop\\Test C#\\template.xlsx";
    string fileTemplate = "C:\\Users\\LV98\\Desktop\\Test C#\\excel_file.xlsx";
    excelApp = new Excel.Application();
    Excel.Workbook wbTarget;
    Excel.Worksheet sh;

    //Create target workbook
    wbTarget = excelApp.Workbooks.Open(fileTemplate);

    //Fill target workbook
    //Open the template sheet
    sh = wbTarget.Worksheets["Sheet2"];
    sh.Copy(wbTarget.Worksheets[1]);


    //Save file
    wbTarget.SaveAs(fileTarget);
    wbTarget.Close(true);
    excelApp.Quit();

}

When I open the new excel file, it opens "Sheet2", just what I was after! But only problem is, there is other sheets saved too.. I will be looking into renaming the new sheet - and delete the rest.


Viewing all articles
Browse latest Browse all 90224

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>