我编写了一个小代码,使用c#将几列从源excel文件复制到另一个excel文件(目标excel文件)。下面是源excel文件的示例图像。
下面是我的代码
string fileTarget = @"C:\Users\sia\Desktop\Excel Automation\destination.xlsx";
string fileTemplate = @"C:\Users\sia\Desktop\Excel Automation\source.xlsx";
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbTemp, wbTarget;
Microsoft.Office.Interop.Excel.Worksheet sh;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbSource = excel.Workbooks.Open(fileTemplate, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetSource = wbSource.Sheets[1];
//Copy all range in this worksheet
WorksheetSource.UsedRange.Copy(Type.Missing);
//Open destination workbook
Microsoft.Office.Interop.Excel.Workbook wbDestination = excel.Workbooks.Open(fileTarget, ReadOnly: false);
Microsoft.Office.Interop.Excel.Worksheet WorksheetDestination = wbDestination.Sheets[1];
WorksheetDestination.UsedRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteAll, Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, Type.Missing, Type.Missing);
wbDestination.SaveAs(@"C:\Users\sia\Desktop\Excel Automation\destination.xlsx");
wbSource.Close();
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
我需要在现有代码中进行哪些地方和什么修改才能获得预期的结果。
谢谢
答案 0 :(得分:0)