【遇到的問題】 POI實現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;
        }
    }
 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章