【问题标题】:not able to copy excel column values to specified range in another excel file无法将 excel 列值复制到另一个 excel 文件中的指定范围
【发布时间】:2018-10-03 14:30:20
【问题描述】:

我编写了一个小代码,使用 c# 将几列从源 excel 文件复制到另一个 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);

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

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

谢谢

【问题讨论】:

  • @ashleedawg - 编辑了帖子。

标签: c# excel office-interop


【解决方案1】:

您需要指定正确的列和范围,否则默认粘贴将进入第一列

workSheet.Range

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多