Over a million developers have joined DZone.

How to Copy Data from a Range of Cells In Java Apps

DZone's Guide to

How to Copy Data from a Range of Cells In Java Apps

Trying to figure out how to copy data from a range of cells in Java apps? Learn how in this quick snippet.

· Java Zone
Free Resource

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

This technical tip show how developers can Copy Range Data with Style in an Excel Workbook inside Java Applications. Copy Range Data Only explained how to copy the data from a range of cells to another range. Aspose.Cells can also copy a range complete with formatting. This article explains how to achieve this task. Aspose.Cells provides a range of classes and methods for working with ranges, for example createRange(), StyleFlag, applyStyle() etc. This example explains how to:

  • Creates a workbook.
  • Fills a number of cells in the first worksheet with data.
  • Creates a range.
  • Creates a style object with specified formatting attributes.
  • Applies the style to the data range.
  • Creates a second range of cells.
  • Copies data with the formatting from the first range to the second range.

Copy a Range of Data with Style  in a Workbook


String filePath = "F:/Downloads/source.xlsx";

//Load your source workbook
Workbook workbook = new Workbook(filePath);

//0-byte array
byte[] workbookData = new byte[0];

//Text save options. You can use any type of separator
TxtSaveOptions opts = new TxtSaveOptions();

//Copy each worksheet data in text format inside workbook data array
for (int idx = 0; idx < workbook.getWorksheets().getCount(); idx++)
    //Save the active worksheet into text format
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    workbook.save(bout, opts);

    //Save the worksheet data into sheet data array
    byte[] sheetData = bout.toByteArray();

    //Combine this worksheet data into workbook data array
    byte[] combinedArray = new byte[workbookData.length + sheetData.length];
    System.arraycopy(workbookData, 0, combinedArray, 0, workbookData.length);
    System.arraycopy(sheetData, 0, combinedArray, workbookData.length, sheetData.length);

    workbookData = combinedArray;

//Save entire workbook data into file
FileOutputStream fout = new FileOutputStream(filePath + ".out.txt");

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.

java ,excel

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}