初识POI操作Excel

org.apache.poi提供开源的Excel工具包

jar包:

poi.jar

poi-ooxml.jar

poi-ooxml-schemas.jar

简单的操作流程:

//创建excel文件
SXSSFWorkbook wb = new SXSSFWorkbook();
//创建sheet 可用循环控制sheet大小
if(){

Sheet sheet = wb.creatSheet();
//创建header
Row row = sheet.createRow((int) 0);//创建一行
row.setHeightInPoints(12);//行高12
CellStyle styleInfo = wb.createCellStyle();//创建单元style
styleInfo.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);//
styleInfo.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);//设置单元背景颜色

Font font = ((XSSFCellStyle) styleInfo).getFont();//获得字体
font.setFontName("微软雅黑");
font.setFontHeightInPoints((short) 10);//10号字
Cell cell = null;
for (int j = 0; j < headers.length; j++) {//head是菜单
sheet.setColumnWidth(j, 4000);//设置列宽
cell = row.createCell(j);//行创建单元
cell.setCellValue(headers[j]);//设置单元value即菜单名字
cell.setCellStyle(styleInfo);//设置单元style
}
//创建header成功
//创建body
CellStyle styleInfo = wb.createCellStyle();
Font font = ((XSSFCellStyle) bodyStyleInfo).getFont();
font.setFontName("微软雅黑");
font.setFontHeightInPoints((short) 10);//10号字

int index = 0;
for(int n = 0;n < num_end;n++){num_end-->Collection<Object[]>中collection的大小
index++;//从第二行开始
row = sheet.createRow((int) index);
row.setHeightInPoints(12);//行高12
Object[] fields = Collection[n];//collection的循环遍历,写法看具体collection对象
for(int k = 0;k < fields.length;k++){//
Cell cell = row.createCell(i);
if(fields[k]==null){
cell.setCellValue("");
}else{
cell.setCellValue(fields[k].toString);
cell.setCellStyle(styleInfo);
}
}
}
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out);
out.toByteArray();

//Servlet下载
ServletOutputStream stream = response.getOutputStream();
        stream.write(ExportExcelUtilPOI.exportExcel("采控需求", headers, list));
        stream.flush();
        stream.close();

面向对象建模:

文本----->Excel(sheet)--->sheet(row)---->row(style+cell)--->cell(value+style)

猜你喜欢

转载自www.cnblogs.com/wqff-biubiu/p/8946621.html