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
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.