XSSFWorkbook的使用
一.创建一个workbook对象,对应着一个excel
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
二.创建一个sheet页
多个sheet页就需要创建多次
String sheetName = "sheet页名称";
XSSFSheet sheet = xssfWorkbook.createSheet(sheetName);
三.创建方法设置一个通用字体样式
/**
*
* @param xssfWorkbook 对象
* @param isCenter 是否居中
* @param fontHeight 字体大小
* @return
*/
public static XSSFCellStyle style(XSSFWorkbook xssfWorkbook, boolean isCenter, int fontHeight){
XSSFCellStyle style = xssfWorkbook.createCellStyle();
if (isCenter){
style.setAlignment(HorizontalAlignment.CENTER); //居中
}
style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框
style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框
style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
style.setWrapText(true); //自动换行
style.setFillBackgroundColor(HSSFColor.PALE_BLUE.index); //背景颜色
XSSFFont font = xssfWorkbook.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeight(fontHeight);
style.setFont(font);
return style;
}
四.创建内容
表格是由多个row和cell组成,一个row代表一行,一个cell代表一行中的一个格子
// 行号
int rowNum = 0;
// 创建第一页的第一行,索引从0开始
XSSFRow row0 = sheet.createRow(rowNum++);
//创建第一行第一个
XSSFCell c00 = row0.createCell(0);
//赋值
c00.setCellValue("测试");
//设置样式
c00.setCellStyle(style(xssfWorkbook,true,15));
//表头文字
String [] text = new String[]{"序号","号码","月份","消费金额"};
//设置跨行,前两个参数是需要合并的开始行数和结束行数,后两个是开始列数和结束列数
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, text.length-1));
//冻结行数,冻结前两行
sheet.createFreezePane( 0, 2, 0, 2 );
//创建第二行用来放表头文字
XSSFRow row1 = sheet.createRow(rowNum++);
//表头数据,循环将表头数据填充到第二行
for (int i = 0; i < text.length; i++) {
XSSFCell c1 = row1.createCell(i);
c1.setCellStyle(style(xssfWorkbook,true,11));
c1.setCellValue(text[i]);
}
//组装测试数据
//DateUtil.thisMonth()使用的是hutool工具类
List<Object[]> objectList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Object [] objects = new Object[text.length];
objects[0] = i+1;
objects[1] = "1318888888"+i;
objects[2] = DateUtil.thisMonth()+i+"月";
objects[3] = i+10;
objectList.add(objects);
}
//将数据放入表格中
for (int i = 0; i < objectList.size(); i++) {
Row temp = sheet.createRow((rowNum++));
Object [] objects = objectList.get(i);
for (int i1 = 0; i1 < objects.length; i1++) {
Cell c = temp.createCell(i1);
c.setCellStyle(style(xssfWorkbook,true,11));
c.setCellValue(objects[i1].toString());
}
}
五.生成excel文件
/**
* 检查是否存在文件夹并创建
* @param path
* @throws IOException
*/
public static void createNewFile(String path) throws IOException {
File file = new File(path);
File fileParent = file.getParentFile();
if(!fileParent.exists()){
fileParent.mkdirs();
}
file.createNewFile();
}
//path为文件存放路径
//createNewFile方法为判断该文件路径是否存在,不存在则自动创建
String path = "d:/测试/测试.xlsx";
createNewFile(path);
FileOutputStream fos = new FileOutputStream(path);
xssfWorkbook.write(fos);
六.效果图
最终的效果图就是这样,简单的excel就可以这样去生成,不过现在也有很多封装了导入导出excel的方法,直接通过注解的方式就可以导入导出,几行代码就够了