依赖
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
</dependencies>
代码
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class ExcelTest {
public static void main(String[] args) {
ExcelTest excelTest=new ExcelTest();
excelTest.createExcel();
}
public void createExcel(){
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("mySheet");
sheet.setDefaultColumnWidth(20);// 默认列宽
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0); //此代码只生成一行数据
//单元格样式
HSSFCellStyle cellStyle = wb.createCellStyle(); // 单元格样式
//字体样式
Font fontStyle = wb.createFont();
fontStyle.setBold(true); // 加粗
fontStyle.setFontName("黑体"); // 字体
fontStyle.setFontHeightInPoints((short) 11); // 大小
fontStyle.setColor(Font.COLOR_RED);//颜色
//字体样式添加到单元格样式中
cellStyle.setFont(fontStyle);
//单元格风格
cellStyle.setAlignment(HorizontalAlignment.CENTER);//左右居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//上下居中
//单元格背景色
cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for(int i=0;i<3;i++){
//生成单元格
HSSFCell cell=row.createCell((int)i);
//单元格内容
cell.setCellValue(i);
//设置单元格样式
cell.setCellStyle(cellStyle);
}
//合并单元格
CellRangeAddress cra =new CellRangeAddress(0, 3, 2, 2); // 起始行, 终止行, 起始列, 终止列
sheet.addMergedRegion(cra);
//输出Excel文件
FileOutputStream output=null;
try {
output= new FileOutputStream("F:\\学习\\workbook.xls");
wb.write(output);
output.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(output!=null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
效果图