Transpose values in excel using C#

前端 未结 3 1093
再見小時候
再見小時候 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:

提交回复
热议问题