Transpose values in excel using C#

前端 未结 3 1094
再見小時候
再見小時候 2021-01-23 10:44

I saw this link - C# Transpose() method to transpose rows and columns in excel sheet in stackoverflow and this is what I am trying to do. But the guy is pretty unhelpful in the

相关标签:
3条回答
  • 2021-01-23 11:09

    This was asked a long time ago but I will let my sollution anyway.

    Refs:

    using Microsoft.Office.Interop.Excel;
    using Excel = Microsoft.Office.Interop.Excel;
    

    The trick here is to get the _Application Variable

    in case you are using VSTO ADDIN with Workbook you can do like this:

    var app = Globals.ThisWorkbook.Parent as _Application;
    

    For other kind of project do like this:

    _Application app2 = new Excel.Application();
    

    My sample (sheet1 is my worksheet):

            var sheet1 = Globals.Planilha1;
            var arr = new string[] 
            {
                "test1",
                "test2",
                "test3",
                "test4",
                "test5",
                "test6",
            };
            
            // For VSTO ADDINS with Workbook
            //var app = Globals.ThisWorkbook.Parent as _Application;
    
            // For any kind of Excel Interop project
            _Application app = new Excel.Application();
    
            sheet1.Range["A1:A" + arr.Length].Value = app.WorksheetFunction.Transpose(arr);
    

    The Transpose function can only deal with arrays, lists won't work.

    Just place the array inside the app.WorksheetFunction.Transpose function and it will work pretty well.

    Output:

    0 讨论(0)
  • 2021-01-23 11:13

    Seems like nobody actually bothered to answer this and its still the top search engine hit for this issue (@ July 2019, go figure...!), so here's my 2 cents... I did not understand the hype about the WorksheetFunction.Transpose method. "Objectifying" things around isn't perhaps the cleanest way to go about this, particularly when using the Excel Interop anyway. At the end of the day, Transpose has been a dynamic parameter of the PasteSpecial() method since time immemorial. So why not use it as such? I think this was what prompted some people to suggest using VBA instead of C#... Anyway, this code works and does what the question requires methinks:

    First get the references right...

    using System;
    using Microsoft.Office.Interop.Excel;
    using Excel = Microsoft.Office.Interop.Excel;
    

    Then try this...

        string filePath = @"P:\Visual Studio 2013\Projects\Debugging\Debugging\test.htm";
        string savePath = @"P:\Visual Studio 2013\Projects\Debugging\Debugging\testing.xls";
    
        var excelApp = new Excel.Application()
        {
            Visible = true      //This is optional
        };
        Workbooks workbook = excelApp.Workbooks;
        workbook.Open(filePath);
    
        Range range = excelApp.get_Range("A9:B15");
        range.Copy();
    
        excelApp.ActiveSheet.Range("A1").PasteSpecial(Transpose: true);     //voila... :)
        range.Delete(XlDeleteShiftDirection.xlShiftToLeft);     //delete original range 
    
        if (!System.IO.File.Exists(savePath))           //is the workbook already saved?
        {
            excelApp.ActiveWorkbook.SaveAs(savePath);   //save
        }
        else
        {
            Console.WriteLine("File \"{0}\" already exists.", savePath);    //or do whatever...
            Console.ReadLine();
            return;
        }
    

    It could be simplified further... but it is more readable like this.

    0 讨论(0)
  • 2021-01-23 11:22

    Is there some reason you need to do this in C#?

    If what you want is just what you state, VBA code can accomplish this also. Just

    • read the transposed range into a variant array
    • clear the worksheet
    • write the variant array back to the worksheet at the cell of your choice.
    • Note that when you write the variant array back to the worksheet, the destination range must be the same size as the array.

    Option Explicit
    Sub TransposeRange()
        Dim RGtoTranspose As Range
        Dim V As Variant
    Set RGtoTranspose = Range("A9:B15")
    V = WorksheetFunction.Transpose(RGtoTranspose)
    
    Cells.Clear
    Range("a1").Resize(UBound(V, 1), UBound(V, 2)).Value = V
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题