项目中导入一下依赖Jar包
<!--Excel文件下载依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
一、单元格样式
HSSFWorkbook wb = new HSSFWorkbook()
HSSFCellStyle cellStyle = wb.createCellStyle();
1.设置边框
cellStyle.setBorderBottom(BorderStyle.THIN);//设置下边框
cellStyle.setBorderLeft(BorderStyle.THIN);//设置左边框
cellStyle.setBorderRight(BorderStyle.THIN);//设置右边框
cellStyle.setBorderTop(BorderStyle.THIN);//设置上边框
2.设置边框颜色
cellStyle.setBottomBorderColor((short)1);
3.设置每个单元格的文字居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
4.设置字体
//通过HSSFWorkbook创建一个HSSFFont
HSSFFont font = workbook.createFont();
//设置一个字体的颜色
//2表示红色
//3表示绿色
//4表示蓝色
//5表示黄色
//6表示紫色
//7表示亮蓝色
//8表示黑色
//9表示白色
font.setColor((short)8);
//设置字体的风格:仿宋_GB2312、黑体
font.setFontName("黑体");
//设置一个字体的大小,此数值的取值与Excel中的字体大小取值一样
font.setFontHeightInPoints((short) 16);
//粗体显示
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//把该字体应用到当前的样式
cellStyle.setFont(font);
5.设置自动换行
cellStyle.setWrapText(true);
6.设置背景色
cellStyle.setFillForegroundColor((short) 13);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
二、表格
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("sheet1");
1.设置列宽
//设置列宽,其中width表示Excel中的列宽值
sheet.setColumnWidth(0, 256*width+184); //第一个参数代表列id(从0开始),第2个参数代表宽度值
2.合并单元格
//firstRow:起始行
//lastRow:结束行
//firstCol:起始列
//lastCol:结束列
CellRangeAddress region = new CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol);
sheet.addMergedRegion(region);