无法将excel列值复制到另一个excel文件中的指定范围

时间:2018-10-03 06:13:53

标签: c# excel office-interop

我编写了一个小代码,使用c#将几列从源excel文件复制到另一个excel文件(目标excel文件)。下面是源excel文件的示例图像。

enter image description here

目标excel文件中的预期结果应如下图所示。 enter image description here

下面是我的代码

    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);

但是我没有得到预期的格式,下面是我得到的结果。 enter image description here

我需要在现有代码中进行哪些地方和什么修改才能获得预期的结果。

谢谢

1 个答案:

答案 0 :(得分:0)

您需要指定适当的列和范围,否则默认情况下,粘贴将进入第一列

workSheet.Range

以供参考:Copy/paste cells in Excel with C#