package export; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class TwoAddMergedRegion { public static void main(String[] args) { // create workbook XSSFWorkbook wb = new XSSFWorkbook(); // 4 column int cellSpan=4; // XSSFSheet sheet = wb.createSheet("My test"); // XSSFRow titleRow = sheet.createRow(0); List cells = new ArrayList(cellSpan); for(int i = 0; i< cellSpan; i++){ cells.add(titleRow.createCell(i)); } // cells.get(0).setCellValue("Hello"); // first merge from A to D sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, cellSpan - 1)); // second merge from A to F sheet.addMergedRegion(new CellRangeAddress(0,0,0,cellSpan + 1)); //Write the Excel file FileOutputStream fileOut = null; try { fileOut = new FileOutputStream("d://myFile2.xlsx"); wb.write(fileOut); fileOut.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }