Monday, 09 March 2020 07:31

Copy Cell Range in Excel in Java

Written by  support iceblue
Rate this item
(0 votes)

This article demonstrates how to copy a cell range within a worksheet or between two worksheets in a single Excel document by using Spire.XLS for Java.

Copy a cell range within a worksheet

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class CopyRow {
    public static void main(String[] args) {

        //Create a Workbook instance
        Workbook wb = new Workbook();

        //Load a sample Excel file
        wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx", ExcelVersion.Version2013);

        //Get the first worksheet
        Worksheet sheet = wb.getWorksheets().get(0);

        //Copy a cell range within a worksheet
        sheet.copy(sheet.getCellRange("A1:H1"),sheet.getCellRange("A10:H10"),true);

        //Save the document
        wb.saveToFile("CopyRangeWithinSheet.xlsx", ExcelVersion.Version2013);
    }
}

Copy Cell Range in Excel in Java

Copy a cell range from one worksheet to another

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class CopyRow {
    public static void main(String[] args) {

        //Create a Workbook instance
        Workbook wb = new Workbook();

        //Load a sample Excel file
        wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx", ExcelVersion.Version2013);

        //Get the first worksheet
        Worksheet sheet1 = wb.getWorksheets().get(0);

        //Get the second worksheet
        Worksheet sheet2 = wb.getWorksheets().get(1);

        //Copy a cell range from sheet 1 to sheet 2
        sheet1.copy(sheet1.getCellRange("A1:H1"),sheet2.getCellRange("A1:H1"),true);

        //Auto fit column width in sheet 2
        for (int i = 0; i < 8; i++) {

            sheet2.autoFitColumn(i+1);
        }

        //Save the document
        wb.saveToFile("CopyRangeBetweenSheets.xlsx", ExcelVersion.Version2013);
    }
}

Copy Cell Range in Excel in Java

Additional Info

  • tutorial_title: