在C#中使用转置复制和粘贴

时间:2018-10-18 13:53:04

标签: c# excel transpose excel-interop

我正在尝试将一系列单元格从一个工作簿复制到另一个工作簿,它可以正常工作,但是当我尝试通过转置使用SaveAs函数时,它给了我一个错误:

  

System.Reflection.TargetInvocationException:“调用目标已抛出异常。”

     

内部异常。   COMException:Range类的PasteSpecial方法失败

这是我的代码:

        private void CopyTranspose(string rawFile, string tempFile, string dataFile, string oldCells, string newCells)
    {
        try
        {
            object missing = Type.Missing;

            //Copying data
            Excel.Application oldApp = new Excel.Application();
            oldApp.Application.DisplayAlerts = false;
            oldApp.Application.Visible = false;
            oldApp.Application.DisplayAlerts = false;
            Excel.Workbook oldWorkBook = oldApp.Workbooks.Open(rawFile);
            Excel.Worksheet oldWorkSheet = oldWorkBook.Worksheets.get_Item(1);
            Excel.Range oldRange = oldWorkSheet.Range[oldCells];
            oldRange.Copy(Type.Missing);

            //Pasting data
            Excel.Application newApp = new Excel.Application();
            Excel.Workbook newWorkBook = newApp.Workbooks.Open(tempFile, 0, false);
            newApp.Application.DisplayAlerts = false;
            newApp.Application.Visible = false;
            newApp.Application.DisplayAlerts = false;
            Excel.Worksheet newWorkSheet = newWorkBook.Worksheets.get_Item(1);
            Excel.Range newRange = newWorkSheet.Range[newCells];
            newRange.Select();

            newWorkSheet.Paste(Type.Missing, Type.Missing);  //This line works but it doesn't do the transpose 

            newRange.PasteSpecial(Excel.XlPasteType.xlPasteValues, 
            Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, true, true); //this line does the transpose but it fails

            oldWorkBook.Close(false, null, null);
            oldApp.Quit();

            //Saving File
            newWorkBook.SaveAs(dataFile, missing, missing, missing, missing, false);
            newWorkBook.Close(false, null, null);
            newApp.Quit();
        }
        catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); }
    }

这是输出窗口上的例外:

  

抛出异常:mscorlib.dll中的'System.Runtime.InteropServices.COMException'   Range类的PasteSpecial方法失败

任何帮助将不胜感激,我不仅在寻找解决方案,而且还了解我的代码有什么问题,谢谢!

0 个答案:

没有答案