如何以编程方式将工作表从一个工作簿复制到另一工作簿
问题描述:
先生,
我有一本具有N张工作表的工作簿,每张工作表都有一个模板文件.现在我需要创建一个新工作簿并使用c#将工作表从现有工作簿复制到新创建的工作簿,我该怎么办?我对excel工作表的编程一点都不熟悉,请帮助我,先生?
Sir,
I have a workbook having N number of sheets, each sheet is having a template file. Now i need to create a new workbook and copy sheets from existing workbook to newly created one using c#.How can i do that?I am not at all familiar with programming with excel sheets, so please help me sir?
答
要使用EXCEL进行编程,您需要在com选项卡中添加对"Microsoft.office.interop.excel"的引用.
使用此 [
For programming with EXCEL, you need to add reference of "Microsoft.office.interop.excel" from com tab.
use this[^] link for coding reference
您好.
在此主题 [ ^ ],请查看第一个答案中的代码.它不能解决您的问题,但是在这里使用,您可以自己解决.
我认为,您的代码会像这样:
Hello.
In this topic[^] please look at code in first answer. It doesn''t solves your problem, but using there, you can solve it by youreself.
I think, your code shoild be like that:
xlWorkbookFrom = xlApp.Workbooks.Open(fullFilenameFrom, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlWorkbookTo = xlApp.Workbooks.Open(fullFilenameTo, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
xlSheetsFrom = xlWorkbookFrom.Sheets as Sheets;
xlSheetsTo = xlWorkbookTo.Sheets as Sheets;
foreach(var sheet in xlSheetsFrom)
{
xlNewSheet = (Worksheet)xlSheetsTo.Add(sheet , Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = sheet.Name;
}
xlWorkbookTo .Save();
xlWorkbookTo .Close(Type.Missing,Type.Missing,Type.Missing);
...//etc
但我真的不确定,这是否行得通,我从不尝试.
But I really don''t sure, that thiswill work, I never try.