POI實現EXCEL單元格合併及邊框樣式
阿新 • • 發佈:2019-01-06
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;
}
}
}