C# – Copy Data from Cells to Other Cells

Generally speaking, if there is a small amount of data, we can enter it in Excel manually. Sometimes, we may meet the same data. For example, data from B1 to B5 is the same as data from A1 to A5. In order to save time, we can copy data in A column to B directly.

Next, I will show how to copy data from source data cells to other cells with C#.

In my example, I have prepared an Excel file Sales Report. The first table is about sales status in January and the second is about in February. Because Product No. and Unit Price are not changed, so we just need to copy data of the two items in first table to second table.  

Original File

Note: this method is based on Spire.XLS as well, so remember to add DLL file as reference in your project.

Details:

Step 1: Load data in Sales Report and initialize worksheet.

            //Load File

            Workbook workbook = new Workbook();

            workbook.LoadFromFile(@"D:\work\My Documents\Sales Report.xlsx");

            Worksheet worksheet = workbook.Worksheets[0];

Step 2: Copy Product No. in January sales report to February report. Confirm source data range and goal data range. Then copy format by giving true value in worksheet.Copy() method.

            worksheet.Copy(worksheet.Range["A3:A9"], worksheet.Range["A14:A20"], true);

Step 3: Copy Unit Price as Step 2.

Step 4: Save and launch the new file.

Complete Coding:

using System;

using Spire.Xls;

 

namespace CopyData

{

    class Copy

    {

        static void Main(string[] args)

        {

            //Load File

            Workbook workbook = new Workbook();

            workbook.LoadFromFile(@"D:\work\My Documents\Sales Report.xlsx");

            Worksheet worksheet = workbook.Worksheets[0];

 

            //Copy Product No

            worksheet.Copy(worksheet.Range["A3:A9"], worksheet.Range["A14:A20"], true);

 

            //Copy Unit Price

            worksheet.Copy(worksheet.Range["C3:C9"],worksheet.Range["C14:C20"],true);

 

            //Save and Launch File

            workbook.SaveToFile("DataCopy.xlsx",ExcelVersion.Version2010);

            System.Diagnostics.Process.Start(workbook.FileName);

 

        }

    }

}

Now, we can get result as following:

—————————————————————

Click Here to learn more about Spire.XLS

Click Here to download Spire.XLS

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s