I want to transpose rows and columns of an excel sheet and save it. I want to use C# transpose() method for this purpose. Can anybody tell how it can be used in C# with exam
Transpose can be accessed as a parameter of PasteSpecial(Transpose: whatever).
I have answered this in full here: Transpose values in excel using C#
First you have to convert excel sheet to datatable and then programmatically transpose rows and columns of datatable.For converting excel sheet to datatable,you can search question on stackoverflow as it has lot of similar questions.For trasposing datatable below code works;
private DataTable GenerateTransposedTable(DataTable inputTable)
{
DataTable outputTable = new DataTable();
// Add columns by looping rows
// Header row's first column is same as in inputTable
outputTable.Columns.Add(inputTable.Columns[0].ColumnName.ToString());
// Header row's second column onwards, 'inputTable's first column taken
foreach (DataRow inRow in inputTable.Rows)
{
string newColName = inRow[0].ToString();
outputTable.Columns.Add(newColName);
}
// Add rows by looping columns
for (int rCount = 1; rCount <= inputTable.Columns.Count - 1; rCount++)
{
DataRow newRow = outputTable.NewRow();
// First column is inputTable's Header row's second column
newRow[0] = inputTable.Columns[rCount].ColumnName.ToString();
for (int cCount = 0; cCount <= inputTable.Rows.Count - 1; cCount++)
{
string colValue = inputTable.Rows[cCount][rCount].ToString();
newRow[cCount + 1] = colValue;
}
outputTable.Rows.Add(newRow);
}
return outputTable;
}
your method is part of the Excel object model but included in C# through Visual Studio Tools for Office / Excel DNA / Managed XLL etc
Object[,] transposedRange = (Object[,])xlApp.WorksheetFunction.Transpose(rng.Value2);
Then paste the transposedRange back into Excel:
xlApp.ActiveSheet.Range("A1").Resize(transposedRange.GetUpperBound(0), transposedRange.GetUpperBound(1)) = transposedRange;