Java匯出Excel合併儲存格
1、問題背景
利用POI匯出Excel表格,在匯出的過程中涉及到雙表頭,即需要合併儲存格
2、實現源碼
/** * * @Project:Report * @Title:MergeCell.java * @Package:com.you.excel * @Description: * @Author:YouHaiDong * @Date:2015年11月4日 下午2:36:46 * @Version: */package com.you.excel;import java.io.FileOutputStream;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRichTextString;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.Region;/** *
合併儲存格
* @ClassName:MergeCell * @Description: * @Author:YouHaiDong * @Date:2015年11月4日 下午2:36:46 * */ public class MergeCell { /** * 合併儲存格 * @Title:MergeCell * @Description: * @param args * @Date:2015年11月4日 下午2:36:46 * @return: void * @throws Exception */ @SuppressWarnings({ resource, deprecation }) public static void main(String[] args) throws Exception { //建立workbook HSSFWorkbook workbook = new HSSFWorkbook(); //建立sheet頁 HSSFSheet sheet = workbook.createSheet(學生表); //建立儲存格 HSSFRow row = sheet.createRow(0); HSSFCell c0 = row.createCell(0); c0.setCellValue(new HSSFRichTextString(學號)); HSSFCell c1 = row.createCell(1); c1.setCellValue(new HSSFRichTextString(姓名)); HSSFCell c2 = row.createCell(2); c2.setCellValue(new HSSFRichTextString(性別)); HSSFCell c3 = row.createCell(3); c3.setCellValue(new HSSFRichTextString(年齡)); HSSFCell c4 = row.createCell(4); c4.setCellValue(new HSSFRichTextString(2015年分數)); HSSFCell c5 = row.createCell(7); c5.setCellValue(new HSSFRichTextString(2014年分數)); HSSFRow row1 = sheet.createRow(1); HSSFCell c6 = row1.createCell(4); c6.setCellValue(new HSSFRichTextString(語文)); HSSFCell c7 = row1.createCell(5); c7.setCellValue(new HSSFRichTextString(數學)); HSSFCell c8 = row1.createCell(6); c8.setCellValue(new HSSFRichTextString(外語)); HSSFCell c9 = row1.createCell(7); c9.setCellValue(new HSSFRichTextString(語文)); HSSFCell c10 = row1.createCell(8); c10.setCellValue(new HSSFRichTextString(數學)); HSSFCell c11 = row1.createCell(9); c11.setCellValue(new HSSFRichTextString(外語)); Region region1 = new Region(0, (short)0, 1, (short)0); Region region2 = new Region(0, (short)1, 1, (short)1); Region region3 = new Region(0, (short)2, 1, (short)2); Region region4 = new Region(0, (short)3, 1, (short)3); Region region5 = new Region(0, (short)4, 0, (short)6); Region region6 = new Region(0, (short)7, 0, (short)9); sheet.addMergedRegion(region1); sheet.addMergedRegion(region2); sheet.addMergedRegion(region3); sheet.addMergedRegion(region4); sheet.addMergedRegion(region5); sheet.addMergedRegion(region6); FileOutputStream stream = new FileOutputStream(d:/student.xls); workbook.write(stream); } }
3、實現結果