下面例子為創建產生一個excel,合併單元格,然後為合併後的單元格添加邊框
- package test;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import org.apache.poi.hssf.usermodel.HSSFCell;
- import org.apache.poi.hssf.usermodel.HSSFCellStyle;
- 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.ss.usermodel.BorderStyle;
- import org.apache.poi.ss.usermodel.Font;
- import org.apache.poi.ss.usermodel.HorizontalAlignment;
- import org.apache.poi.ss.util.CellRangeAddress;
- import org.apache.poi.ss.util.RegionUtil;
- public class ExcelPoiTest {
- public static void main(String[] args) {
- HSSFWorkbook workbook = new HSSFWorkbook(); // 創建一個excel
- // excel生成過程: excel–>sheet–>row–>cell
- HSSFSheet sheet = workbook.createSheet(“test”); // 為excel創建一個名為test的sheet頁
- HSSFRow row = sheet.createRow(1); // 創建一行,參數2表示第一行
- HSSFCell cellB2 = row.createCell(1); // 在B2位置創建一個單元格
- HSSFCell cellB3 = row.createCell(2); // 在B3位置創建一個單元格
- cellB2.setCellValue(“單元格B2”); // B2單元格填充內容
- cellB3.setCellValue(“單元格B3”); // B3單元格填充內容
- HSSFCellStyle cellStyle = workbook.createCellStyle(); // 單元格樣式
- Font fontStyle = workbook.createFont(); // 字體樣式
- fontStyle.setBold(true); // 加粗
- fontStyle.setFontName(“黑體”); // 字體
- fontStyle.setFontHeightInPoints((short) 11); // 大小
- // 將字體樣式添加到單元格樣式中
- cellStyle.setFont(fontStyle);
- // 邊框,居中
- cellStyle.setAlignment(HorizontalAlignment.CENTER);
- cellStyle.setBorderBottom(BorderStyle.THIN);
- cellStyle.setBorderLeft(BorderStyle.THIN);
- cellStyle.setBorderRight(BorderStyle.THIN);
- cellStyle.setBorderTop(BorderStyle.THIN);
- cellB2.setCellStyle(cellStyle); // 為B2單元格添加樣式
- // 合併單元格
- CellRangeAddress cra =new CellRangeAddress(1, 3, 1, 3); // 起始行, 終止行, 起始列, 終止列
- sheet.addMergedRegion(cra);
- // 使用RegionUtil類為合併後的單元格添加邊框
- RegionUtil.setBorderBottom(1, cra, sheet); // 下邊框
- RegionUtil.setBorderLeft(1, cra, sheet); // 左邊框
- RegionUtil.setBorderRight(1, cra, sheet); // 有邊框
- RegionUtil.setBorderTop(1, cra, sheet); // 上邊框
- // 輸出到本地
- String excelName = “/myExcel.xls”;
- FileOutputStream out = null;
- try {
- out = new FileOutputStream(excelName);
- workbook.write(out);
- out.flush();
- out.close();
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (out != null)
- try {
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- out = null;
- }
- }
- }
生成的excel樣式為

簡單說明:
1.excel生成過程: excel–>sheet–>row–>cell 2.索引從0開始
3.合併單元格後保留最左上角的單元格(B3單元格被B2單元格覆蓋)
4.合併後單元格邊框通過RegionUtil設置,如果刪除以下代碼
- // 使用RegionUtil類為合併後的單元格添加邊框
- RegionUtil.setBorderBottom(1, cra, sheet); // 下邊框
- RegionUtil.setBorderLeft(1, cra, sheet); // 左邊框
- RegionUtil.setBorderRight(1, cra, sheet); // 有邊框
- RegionUtil.setBorderTop(1, cra, sheet); // 上邊框
效果為:

可以看到只有B2單元格有邊框。
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/225521.html
微信掃一掃
支付寶掃一掃