我需要将工作表从一个工作簿复制到另一个工作簿中,但我有点卡住了。前提是我有一个“主”工作簿,其中存储了许多报告的模板,然后我需要创建特定工作表的空白副本并将其添加到新工作簿中。
这是我到目前为止所拥有的:
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() 时,它将原始工作簿中的所有工作表保存到新工作簿中。关于如何纠正这个问题有什么想法吗?
提前致谢,
Sonny
您还可以使用Sheet.Copy()
method.
基本上,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 链接 https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.copy
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)