跨文档复制excel sheet 页
public class CopyManager { public static KeyValuePair<bool,string> CopyWithMessage(string sourcefile, string destfile) { Microsoft.Office.Interop.Excel.Application application = new Excel.Application(); Excel.Workbook sourcebook = null; Excel.Workbook destinationbook = null; try { application.Visible = false; application.DisplayAlerts = false; sourcebook = application.Workbooks.Open(sourcefile, false, true, Type.Missing, Type.Missing , Type.Missing, Type.Missing, Type.Missing, Type.Missing , Type.Missing, Type.Missing, Type.Missing, Type.Missing); try { destinationbook = application.Workbooks.Open(destfile, false, Type.Missing, Type.Missing, Type.Missing , Type.Missing, true, Type.Missing, Type.Missing , Type.Missing, Type.Missing, Type.Missing, XlCorruptLoad.xlNormalLoad); } catch (Exception ex) { return new KeyValuePair<bool, string>(false, ex.Message); } int copycount = sourcebook.Worksheets.Count; int destsheetcount = destinationbook.Worksheets.Count; Excel.Worksheet lastworksheet = destinationbook.Worksheets[destsheetcount]; Excel.Worksheet firstworksheet = destinationbook.Worksheets[1]; for (int i = 1; i <= copycount; i++) { Excel.Worksheet worksheet = sourcebook.Worksheets[i]; if (worksheet.Name == "Cover") { worksheet.Copy(firstworksheet, Type.Missing); } if (worksheet.Name == "Disclaimers") { worksheet.Copy(Type.Missing, lastworksheet); } } destinationbook.CheckCompatibility = false; if (Path.GetExtension(destfile) == ".xlsx") { destinationbook.Save(); return new KeyValuePair<bool, string>(true, destfile); } else { string savefilename = Path.Combine(Path.GetDirectoryName(destfile), Path.GetFileNameWithoutExtension(destfile) + ".xlsx"); if (File.Exists(savefilename)) { File.Delete(savefilename); } destinationbook.SaveAs(savefilename, XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, false, Type.Missing, Type.Missing, Type.Missing); return new KeyValuePair<bool, string>(true, savefilename); } //destinationbook.AutoUpdateSaveChanges = false; //destinationbook.Save(); } catch (Exception ex) { return new KeyValuePair<bool, string>(false, ex.Message); ; } finally { if (sourcebook != null) { sourcebook.Close(false, Type.Missing, Type.Missing); } if (destinationbook != null) { destinationbook.Close(true, Type.Missing, Type.Missing); } application.Quit(); // 强制回收 Excel 进程 int geneID = System.GC.GetGeneration(application); sourcebook = null; destinationbook = null; application = null; System.GC.Collect(geneID); ErrorManager.KillErrorProcessNow(); } } }