Hi, I want to move a column from one position to other position. I used cells copyColumn method but it is replacing the column in destination position but i don’t want to replace instead it simply cut and paste the column at source position to destination position. Enclosed the input and output and below is the sample code.
public static void main(String[] args) {
setAsposeExcelLicense();
// Instantiate a new workbook
Workbook workbook = null;
try {
workbook = new Workbook(Thread.currentThread().getContextClassLoader().getResourceAsStream("copy-columns.xlsx"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the Cells collection in the first worksheet
Cells cells = workbook.getWorksheets().get(0).getCells();
cells.copyColumn(cells, 5, 0);
//cells.deleteColumn(6);
// Save the excel file
try {
//Auto-fit rows in the worksheet
workbook.getWorksheets().get(0).autoFitRows();
workbook.save("copycolumns_out.xlsx");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Print message
System.out.println("Process completed successfully");
}
Yes, the copyColumn method will copy and paste the existing contents in the destination column, overwriting any existing data. First, you need to insert the column at the 0 index and then copy the column to the desired position. After copying, you can remove the original column from which you have copied the data. See the updated sample code segment for your reference.
e.g., Sample code:
// Get the Cells collection in the first worksheet
Cells cells = workbook.getWorksheets().get(0).getCells();
cells.insertColumn(0);
cells.copyColumn(cells, 6, 0);
cells.deleteColumn(6);