关于C#:C# |
您所在的位置:网站首页 › excel表格从一个工作簿复制到另一个工作簿 › 关于C#:C# |
我需要将工作表从一个工作簿复制到另一个工作簿中,但我有点卡住了。 前提是我有一个"主"工作簿,其中存储了许多报告的模板,然后需要创建特定工作表的空白副本并将其添加到新工作簿中。 这是我到目前为止的内容: 12345678910111213141516171819202122232425262728293031323334353637383940private 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之后,尝试在代码中添加以下行: 12345//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链接 我意识到这是一个比较晚的答复,但是我为此付出了很多努力,因此我认为我会发布解决方案,以便它可以帮助遇到此问题的其他人。 想要多次填写模板表: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 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 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |