public class MergedCells { /** 測試使用的POI版本是3.1 * @param args */ public static void main(String[] args) throws IOException { HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("new sheet"); HSSFRow row = sheet.createRow(1); HSSFCell cell = row.createCell((short)1); cell.setCellValue("This is a test of merging"); //1.生成字體對象 HSSFFont font = wb.createFont(); font.setFontHeightInPoints((short) 10); font.setFontName("新宋體"); font.setColor(HSSFColor.BLUE.index); font.setBoldweight((short) 0.8); //2.生成樣式對象 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); style.setFont(font); //調用字體樣式對象 style.setWrapText(true); //增長表格邊框的樣式 例子 style.setBorderTop(HSSFCellStyle.BORDER_DOUBLE); style.setBorderLeft(HSSFCellStyle.BORDER_DOUBLE); style.setTopBorderColor(HSSFColor.GOLD.index); style.setLeftBorderColor(HSSFColor.PLUM.index); //3.單元格應用樣式 cell.setCellStyle(style); //新版用法 3.8版 // sheet.addMergedRegion(new CellRangeAddress( // 1, //first row (0-based) from 行 // 2, //last row (0-based) to 行 // 1, //first column (0-based) from 列 // 1 //last column (0-based) to 列 // )); //表示合併B2,B3 sheet.addMergedRegion(new Region( 1, //first row (0-based) (short)1, //first column (0-based) 2, //last row (0-based) (short)1 //last column (0-based) )); //合併疊加 表示合併B3 B4。可是B3已經和B2合併了,因此,變成B2:B4合併了 sheet.addMergedRegion(new Region( 2, //first row (0-based) (short)1, //first column (0-based) 3, //last row (0-based) (short)1 //last column (0-based) )); //一下代碼表示在D4 cell 插入一段字符串 HSSFRow row2 = sheet.createRow(3); HSSFCell cell2 = row2.createCell((short)3); cell2.setCellValue("this is a very very very long string , please check me out."); //cell2.setCellValue(new HSSFRichTextString("我是單元格!")); // Write the output to a file FileOutputStream fileOut = new FileOutputStream("workbook.xls"); wb.write(fileOut); fileOut.close(); } }