rearranging data inside a excel sheet c#

ankit goel 766 Reputation points
2022-12-03T13:39:45.793+00:00

I have an excel file which contains data in the following format
266789-image.png

I want to rearrange the data in the following format.
266837-image.png

I am using office.interop assembly for opening and editing excel

Developer technologies C#
{count} votes

Accepted answer
  1. Jack J Jun 25,296 Reputation points
    2022-12-05T04:52:39.247+00:00

    @ankit goel , Welcome to Microsoft Q&A, you could try the following code to rearrange the data in the excel.

                Excel.Application excel = null;  
                excel = new Excel.Application();  
                //excel.Visible = true;  
                Excel.Workbook wkb = null;  
                wkb = excel.Workbooks.Open("C:\\Users\\Administrator\\Desktop\\Test.xlsx");  
                Excel.Worksheet sheet = wkb.Sheets[1];  
                Excel.Range range1 = sheet.UsedRange;  
                // Read all data from data range in the worksheet  
                var valueArray = (object[,])range1.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);  
                int m = 1;  
                sheet.Cells.ClearContents();  
                for (int i = 1; i <= valueArray.GetLength(0); i++)  
                {  
                    if (i % 2 != 0)  
                    {  
                        sheet.Cells[m, 1].Value = valueArray[i, 1];  
                        sheet.Cells[m, 2].Value = valueArray[i, 2];  
                        sheet.Cells[m, 3].Value = valueArray[i+1, 1];  
                        sheet.Cells[m, 4].Value = valueArray[i+1, 2];  
                        m++;  
                    }  
                      
                }  
               
                wkb.Save();  
                wkb.Close(true);  
                excel.Quit();  
       
    

    Tested result:

    267013-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.