我需要把工作表从一个工作簿复制到另一个工作簿,我有点卡住了。前提是我有一个“主”工作簿,用于存储多个报表的模板,然后我需要创建一个特定工作表的空白副本并将其添加到新工作簿中。
这就是我目前所拥有的:
private void CreateNewWorkbook(Tables table)
{
Excel.Application app = null;
Excel.Workbook book = null;
Excel.Worksheet sheet = null;
try
{
string startPath = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
string filePath = System.IO.Path.Combine(startPath, "sal1011forms.xls");
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
app = new Excel.Application();
book = app.Workbooks.Open(filePath);
sheet = (Excel.Worksheet)book.Worksheets.get_Item((int)table + 1);
sfd.AddExtension = true;
sfd.FileName = table.ToString() + ".xls";
sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (sfd.ShowDialog() == true)
{
sheet.SaveAs(sfd.FileName);
}
}
finally
{
if (book != null)
{
book.Close();
}
if (app != null)
{
app.Quit();
}
this.ReleaseObject(sheet);
this.ReleaseObject(book);
this.ReleaseObject(app);
}
}
目前唯一的问题是,当我在工作表上调用.save()时,它会将原始工作簿中的所有工作表保存到新工作簿中。关于如何纠正这个问题有什么想法吗?
提前谢谢你,
桑尼
最佳答案
也可以使用sheet.copy()方法。
基本上,sheet.copy复制工作表,并同时自动创建新工作簿。
在调用worksheets.get_item之后,尝试将以下行添加到代码中:
//Copies sheet and puts the copy into a new workbook
sheet.Copy(Type.Missing, Type.Missing);
//sets the sheet variable to the copied sheet in the new workbook
sheet = app.Workbooks[2].Sheets[1];
这里还有copy()函数的引用:
MSDN Link
关于c# - C#-如何将单个Excel工作表从一个工作簿复制到另一个工作簿?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3808368/