public void test(Application xlApp) { string file = @"C:\Temp\a.xlsx"; Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(file); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; xlWorksheet.Range["A1"].EntireRow.Copy(); Excel.Workbook xlWorkbookNew = xlApp.Workbooks.Add(); Excel._Worksheet xlWorksheetNew = xlWorkbookNew.Sheets[1]; Worksheet activeSheet = xlWorkbookNew.ActiveSheet; activeSheet.Paste(); xlWorkbook.Close(false); xlWorkbookNew.SaveAs(Path.Combine(@"C:\Temp", Path.GetFileName(file))); xlWorkbookNew.Close(true); CloseExcel(); } public void CloseExcel(Application xlApp) { try { if (xlApp != null) { xlApp.Quit(); if (Marshal.IsComObject(xlApp)) Marshal.ReleaseComObject(xlApp); } } catch (Exception ex) { } }
Edit:
I was going to get into low-level material, but did not know your level of knowledge. If you need good performance, do not use Copy / Paste. Here I will show you a couple of simple tricks. First write to all cells at once:
object[,] values = (object[,])Array.CreateInstance(typeof(object), new int[2] { rowCount, ColumnCount }, new int[2] { 1, 1 });
// Fill in the values ββhere, and then write the data in Excel in one fell swoop:
using (var targetRange = xlApp.Range[topLeft + startRow + ":" + rightBottom + endRow].WithComCleanup()) { targetRange.Resource.Value2 = values; }
Secondly, pay attention to .WithComCleanup() - when encoding VSTO, you need to know about unmanaged memory management - http://jake.ginnivan.net/vsto-com-interop .
source share