packagecom.clz.testexportexcel;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.OutputStream;importjava.util.ArrayList;importjava.util.List;importorg.apache.poi.hssf.usermodel.HSSFCell;importorg.apache.poi.hssf.usermodel.HSSFCellStyle;importorg.apache.poi.hssf.usermodel.HSSFFont;importorg.apache.poi.hssf.usermodel.HSSFRow;importorg.apache.poi.hssf.usermodel.HSSFSheet;importorg.apache.poi.hssf.usermodel.HSSFWorkbook;importorg.apache.poi.ss.usermodel.HorizontalAlignment;/*** 生成导出excel
*@authorAdministrator
**/
public classTestExportExcel {public static voidmain(String[] args) {
String exportFileName= "testExcel.xls";
String exportFilePath= "E:\\testExcel";
List excelModels = new ArrayList();
ExcelModel em1= new ExcelModel("张三", 18, "123456", "上海");
ExcelModel em2= new ExcelModel("李四", 20, "456789", "南京");
ExcelModel em3= new ExcelModel("王五", 22, "987412", "杭州");
excelModels.add(em1);
excelModels.add(em2);
excelModels.add(em3);
String exportExcel=exportExcel(excelModels, exportFilePath, exportFileName);
System.out.println(exportExcel);
}/*** 导出excel
*@paramexcelModel 数据实体类
*@paramexportFilePath 导出文件路径
*@paramexportFileName 导出文件名称
*@return生成文件路径*/
public static String exportExcel(ListexcelModels, String exportFilePath, String exportFileName) {
String fileUrl= null;
HSSFWorkbook wb= null;
OutputStream os= null;try{//判断文件夹是否存在,不存在就创建
File fileDir = newFile(exportFilePath);if(!fileDir.exists()) {
fileDir.mkdirs();
}/*** 生成excel文件*/
//第一步,创建一个webbook,对应一个Excel文件
wb = newHSSFWorkbook();//第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("用户信息导出");//第三步,在sheet中添加表头第0行
HSSFRow row = sheet.createRow((int) 0);//第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style =wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);//居中格式
HSSFFont font =wb.createFont();
font.setColor(HSSFFont.COLOR_RED);//HSSFColor.VIOLET.index//字体颜色//把字体应用到当前的样式
style.setFont(font);
HSSFCell cell=null;//表头(与实体类数据一一对应)
String[] headers={"姓名", "年龄", "电话", "地址"};for(int i=0;i
cell= row.createCell((short) i);
cell.setCellValue(headers[i]);
cell.setCellStyle(style);
}//写数据到excel
for (int i = 0; i < excelModels.size(); i++) {
ExcelModel em=excelModels.get(i);//创建行(从第二行开始)
row = sheet.createRow((int) i + 1);//创建列并赋值
row.createCell(0).setCellValue(em.getName());
row.createCell(1).setCellValue(em.getAge());
row.createCell(2).setCellValue(em.getPhone());
row.createCell(3).setCellValue(em.getAddress());
}//写入文件
fileUrl = exportFilePath + File.separator +exportFileName;
os= newFileOutputStream(fileUrl);
wb.write(os);
os.flush();
}catch(Exception e) {
e.printStackTrace();
}finally{if(os != null) {try{
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}if(wb != null) {try{
wb.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}if(fileUrl != null && newFile(fileUrl).exists()) {returnfileUrl;
}return null;
}
}