java-poi创建模板
阅读原文时间:2023年07月09日阅读:2

package com.jy.demo.web;

import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TestExcel {

 public static void main(String\[\] args) throws Exception {  
    Workbook wb = new XSSFWorkbook();  // or new XSSFWorkbook();

    Sheet sheet = wb.createSheet("sheet1");  
    Row rowt = sheet.createRow(0);

    Cell cellt = rowt.createCell(0);  
    cellt.setCellValue("学号");

    Cell cell1t = rowt.createCell(1);  
    cell1t.setCellValue("姓名");

    Cell cell2t11 = rowt.createCell(2);  
    cell2t11.setCellValue("性别");

    Cell cell2t = rowt.createCell(3);  
    cell2t.setCellValue("科目");

    Cell cell2t1 = rowt.createCell(4);  
    cell2t1.setCellValue("成绩");

    // 创建单元格样式对象  
    XSSFCellStyle alignStyle = (XSSFCellStyle) wb.createCellStyle();  
    alignStyle.setAlignment(XSSFCellStyle.ALIGN\_CENTER); // 居中对齐  
    alignStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL\_CENTER);  
    cellt.setCellStyle(alignStyle);

    int y = 2;  
    int num = 0;  
    for (int i = 1; i <= 30; i = i + 3) {  
        num++;  
        Row row1 = sheet.createRow(i);

        Cell cell1 = row1.createCell(0);  
        sheet.addMergedRegion(CellRangeAddress.valueOf("$A$" + y + ":$A$"+ (y + 2)));  
        cell1.setCellValue("00" + num);  
        cell1.setCellStyle(alignStyle);

        Cell cell2 = row1.createCell(1);  
        sheet.addMergedRegion(CellRangeAddress.valueOf("$B$" + y + ":$B$"+ (y + 2)));  
        cell2.setCellValue("张三");  
        cell2.setCellStyle(alignStyle);

        Cell cell21 = row1.createCell(2);  
        sheet.addMergedRegion(CellRangeAddress.valueOf("$C$" + y + ":$C$"+ (y + 2)));  
        cell21.setCellValue("男");  
        cell21.setCellStyle(alignStyle);

        y = y + 3;

        Cell cell3 = row1.createCell(3);  
        cell3.setCellValue("语文");

        Row row2 = sheet.createRow(i + 1);  
        Cell cellr2 = row2.createCell(3);  
        cellr2.setCellValue("数学");

        Row row3 = sheet.createRow(i + 2);  
        Cell cellr3 = row3.createCell(3);  
        cellr3.setCellValue("英语");

        Cell cell4 = row1.createCell(4);  
        cell4.setCellValue("1222");

        Cell cell41 = row2.createCell(4);  
        cell41.setCellValue("98");

        Cell cell411 = row3.createCell(4);  
        cell411.setCellValue("981");

    }  
    FileOutputStream fileOut = new FileOutputStream("E:\\\\workbook.xls");  
    wb.write(fileOut);  
    fileOut.close();  
 }

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器