将Excel工作表复制到其他工作簿

时间:2019-05-29 08:31:12

标签: c# excel

我正在尝试将工作表复制到目标工作簿的最后一个工作表中的另一个工作簿。

我的工作簿和工作表是这样创建的:

public Microsoft.Office.Interop.Excel.Workbook xlWorkbookMatrix;
public Microsoft.Office.Interop.Excel._Worksheet xlWorksheetMatrix;

我尝试使用worksheet.copy:

xlWorksheetMatrix.Copy(Type.Missing, xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);

和工作表。UsedRange.Copy:

xlWorksheetMatrix.UsedRange.Copy(xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);

使用两种不同的方法,我总是会出错。

对于工作表。复制:

System.Runtime.InteropServices.COMException occured in System.Dynamic.dll The Copy-property of the worksheet object can't be assigned

对于工作表。UsedRange.Copy:

System.Runtime.InteropServices.COMException occured in System.Dynamic.dll The Copy-property of the Range object can't be assigned

1 个答案:

答案 0 :(得分:0)

有一个要多次填写的模板工作表,希望对您有所帮助:

public void test()
{

    Excel.Application excelApp;

    string fileTarget = "C:\target.xlsx";
    string fileTemplate = "C:\template.xlsx";
    excelApp = new Excel.Application();
    Excel.Workbook wbTemp, wbTarget;
    Excel.Worksheet sh;

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

    //Fill target workbook
    //Open the template sheet
    sh = wbTarget.Worksheets["TEMPLATE"];
    //Fill in some data
    sh.Cells[1, 1] = "HELLO WORLD!";
    //Rename sheet
    sh.Name = "1. SHEET";


    //Save file
    wbTarget.SaveAs(fileTarget);

    //Iterate through the rest of the files
    for (int i = 1; i < 3; i++)
    {
        //Open template file in temporary workbook
        wbTemp = excelApp.Workbooks.Open(fileTemplate);

        //Fill temporary workbook
        //Open the template sheet
        sh = wbTemp.Worksheets["TEMPLATE"];
        //Fill in some data
        sh.Cells[1, 1] = "HELLO WORLD! FOR THE " + i + ".TH TIME";
        //Rename sheet
        sh.Name = i + ". SHEET";

        //Copy sheet to target workbook
        sh.Copy(wbTarget.Worksheets[1]);
        //Close temporary workbook without saving
        wbTemp.Close(false);
    }

    //Close and save target workbook
    wbTarget.Close(true);
    //Kill excelapp
    excelApp.Quit();
}