【问题标题】:Copying excel worksheet to a different workbook将excel工作表复制到不同的工作簿
【发布时间】:2019-05-29 08:31:12
【问题描述】:

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

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

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]);

和 worksheet.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

对于 worksheet.UsedRange.Copy:

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

【问题讨论】:

    标签: c# excel


    【解决方案1】:

    有一个你想多次填写的模板表,希望这会有所帮助:

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      • 2017-09-18
      • 1970-01-01
      • 2017-08-24
      相关资源
      最近更新 更多