[英]Copying excel worksheet to a different workbook
I'm trying to copy a worksheet to a different workbook into the last worksheet of the target workbook. 我正在尝试将工作表复制到另一个工作簿到目标工作簿的最后一个工作表。
My workbooks and worksheets are created like this: 我的工作簿和工作表是这样创建的:
public Microsoft.Office.Interop.Excel.Workbook xlWorkbookMatrix;
public Microsoft.Office.Interop.Excel._Worksheet xlWorksheetMatrix;
I tried using worksheet.copy: 我尝试使用worksheet.copy:
xlWorksheetMatrix.Copy(Type.Missing, xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);
and worksheet.UsedRange.Copy: 和worksheet.UsedRange.Copy:
xlWorksheetMatrix.UsedRange.Copy(xlWorkbookEvaluation.Sheets[xlWorkbookEvaluation.Sheets.Count]);
With both different methods I always get an error. 使用两种不同的方法我总是会遇到错误。
For worksheet.Copy: 对于工作表。复制:
System.Runtime.InteropServices.COMException occured in System.Dynamic.dll The Copy-property of the worksheet object can't be assigned
For worksheet.UsedRange.Copy: 对于worksheet.UsedRange.Copy:
System.Runtime.InteropServices.COMException occured in System.Dynamic.dll The Copy-property of the Range object can't be assigned
Having a template sheet you want to fill many times, Hope this helps : 有一个模板表,你想填多次,希望这有助于:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.