简体   繁体   English

使用 C# 在 excel 中转置值

[英]Transpose values in excel using C#

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.我看到了这个链接 - C# Transpose() 方法在 stackoverflow 中转置 Excel 表中的行和列,这就是我想要做的。 But the guy is pretty unhelpful in the answers as he does not provide the full information needed.但是这个人在答案中非常无益,因为他没有提供所需的完整信息。 I am simply wanting to transpose cells A9:B15 in my excel sheet and then copy them either into a new xls file, a new worksheet, or better yet delete the current worksheet contents and replace it with the newly transposed paste contents.我只是想在我的 Excel 表格中转置单元格 A9:B15,然后将它们复制到一个新的 xls 文件、一个新的工作表中,或者更好的是删除当前的工作表内容并将其替换为新转置的粘贴内容。 Clearly it can be done through the WorksheetFunction.Transpose method but I can't seem to get it to work as I don't know what rng or value2 are?显然它可以通过 WorksheetFunction.Transpose 方法完成,但我似乎无法让它工作,因为我不知道 rng 或 value2 是什么? I could create a datatable but surly using this method seems a more appropriate way of doing it.我可以创建一个数据表,但使用这种方法似乎是一种更合适的方法。 Here is the code from the stackoverflow question.这是来自stackoverflow问题的代码。 . .

Object[,] transposedRange = (Object[,])xlApp.WorksheetFunction.Transpose(rng.Value2);

xlApp.ActiveSheet.Range("A1").Resize(transposedRange.GetUpperBound(0), transposedRange.GetUpperBound(1)) = transposedRange;

Here is my code so far:到目前为止,这是我的代码:

        Application excel = new Application();
        Workbook wb = excel.Workbooks.Open(@"P:\Visual Studio 2013\Projects\Debugging\Debugging\test.htm");
        Microsoft.Office.Interop.Excel.Range rng = excel.get_Range("A9:B15");
        Object[,] transposeRange = (Object[,])excel.WorksheetFunction.Transpose(rng);
        transposeRange = excel.ActiveSheet.Range("A1").Resize(transposeRange.GetUpperBound(0), transposeRange.GetUpperBound(1));
        wb.SaveAs(@"P:\Visual Studio 2013\Projects\Debugging\Debugging\testing.xls");

Not sure if I have done the rng right.不确定我是否正确完成了 rng。 I am so confused by this.我对此很困惑。

Is there some reason you need to do this in C#?有什么理由需要在 C# 中执行此操作吗?

If what you want is just what you state, VBA code can accomplish this also.如果您想要的正是您所说的,VBA 代码也可以实现这一点。 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

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.似乎没有人真正愿意回答这个问题,它仍然是这个问题的热门搜索引擎(@ 2019 年 7 月,去图……!),所以这是我的 2 美分……我不明白关于 WorksheetFunction 的炒作。转置法。 "Objectifying" things around isn't perhaps the cleanest way to go about this, particularly when using the Excel Interop anyway. “客观化”周围的事物可能不是解决此问题的最简洁方法,尤其是在无论如何使用 Excel Interop 时。 At the end of the day, Transpose has been a dynamic parameter of the PasteSpecial() method since time immemorial.归根结底,自远古以来,转置一直是 PasteSpecial() 方法的动态参数。 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:我认为这就是促使一些人建议使用 VBA 而不是 C# 的原因……无论如何,这段代码可以工作,并且可以满足我认为的问题:

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.它可以进一步简化......但它更易于阅读。

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这里的技巧是获取 _Application 变量

in case you are using VSTO ADDIN with Workbook you can do like this:如果您将 VSTO ADDIN 与 Workbook 一起使用,您可以这样做:

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):我的示例(sheet1 是我的工作表):

        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. Transpose 函数只能处理数组,列表不起作用。

Just place the array inside the app.WorksheetFunction.Transpose function and it will work pretty well.只需将数组放在 app.WorksheetFunction.Transpose 函数中,它就会工作得很好。

Output:输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM