public class HelloworldPoi {
public static void main(String[] args) throws IOException {
//创建一个Excel文件对象
HSSFWorkbook excel = new HSSFWorkbook();
//创建 一个sheet对象
HSSFSheet sheet=excel.createSheet("hello world");
//创建10行和10列
//1.设置表头的值
Row row0=sheet.createRow(0);
LocalDate date=LocalDate.now();
String dateString= DateTimeFormatter.ofPattern("yyyy/MM/dd").format(date);
//设置字体颜色加粗
//创建一个列样式对象
CellStyle style=excel.createCellStyle();
HSSFFont font =excel.createFont();
font.setColor(HSSFColor.BLACK.index);
font.setBold(true);
//font.setFontName("Arial Black");
style.setFont(font);
Cell cell=row0.createCell(0);
cell.setCellStyle(style);
cell.setCellValue("导出日期:"+dateString);
sheet.setColumnWidth(0,25*256);
Row row=sheet.createRow(1);
sheet.setColumnWidth(0,25*256);
sheet.setColumnWidth(1,25*256);
sheet.setColumnWidth(2,25*256);
sheet.setColumnWidth(3,25*256);
sheet.setColumnWidth(4,25*256);
CellStyle cellStyle=excel.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.CORNFLOWER_BLUE.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
HSSFFont font1 =excel.createFont();
font1.setColor(HSSFColor.WHITE.index);
font1.setBold(true);
cellStyle.setFont(font1);
Cell cell10=row.createCell(0);
cell10.setCellValue("第一列");
cell10.setCellStyle(cellStyle);
Cell cell11=row.createCell(1);
cell11.setCellValue("第二列");
cell11.setCellStyle(cellStyle);
Cell cell12=row.createCell(2);
cell12.setCellValue("第三列");
cell12.setCellStyle(cellStyle);
Cell cell13=row.createCell(3);
cell13.setCellValue("第四列");
cell13.setCellStyle(cellStyle);
Cell cell14=row.createCell(4);
cell14.setCellValue("第五列");
cell14.setCellStyle(cellStyle);
//设置背景色
//2.循环设置数据列的值
for (int i=2;i<5;i++){
Row row1=sheet.createRow(i);
for (int j=0;j<5;j++){
row1.createCell(j).setCellValue("第"+i+"行"+j+"列值:"+String.valueOf(i*j));
}
}
FileOutputStream fileOutputStream=new FileOutputStream("D:\\helloword.xlsx");
excel.write(fileOutputStream);
excel.close();
fileOutputStream.close();
}
}
效果如下:
更多用法可参考poi官网
https://poi.apache.org/components/spreadsheet/quick-guide.html#WorkingWithFonts