1.导入 poi jar包。
2.java 后台代码
package com.admin.bug.dao;
import java.io.File;
import java.io.FileOutputStream;import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.HSSFColor;public class CreateExecldao {
/** * 获取单元格行 * @param wb * @param rowname * @param title * @return */ public HSSFRow getRow(HSSFWorkbook wb,String rowname[],String title) { HSSFRow row=getSheet(wb, title).createRow((int)0); for(int i=0;i<rowname.length;i++){ HSSFCell cell=row.createCell(i); cell.setCellValue(rowname[i]); cell.setCellStyle(setExeclStyle2(wb)); } return row; } /** * 获取表格 * @param wb * @param title * @return */ public HSSFSheet getSheet(HSSFWorkbook wb,String title) { try{ HSSFSheet sheet=wb.createSheet(title); sheet.setDefaultColumnWidth(12); return sheet; }catch(Exception e){ return wb.getSheet(title); } } /** * 设置表格格式 * @param wk * @return */ public HSSFCellStyle setExeclStyle(HSSFWorkbook wb) { HSSFCellStyle style=wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中 style.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框 style.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框 style.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框 style.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框 style.setWrapText(true); return style; } /** * 设置字体 * @param wb * @return */ @SuppressWarnings("unused") public HSSFFont setFont(HSSFWorkbook wb){ HSSFFont font=wb.createFont(); font.setFontName("微软雅黑"); if(font==null){ return font; }else{ return wb.getFontAt((short) 0); } } /** * 样式2 * @param wb * @return */ public HSSFCellStyle setExeclStyle2(HSSFWorkbook wb){ // 生成一个样式 HSSFCellStyle style = wb.createCellStyle(); // 设置这些样式 style.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 生成一个字体 HSSFFont font = wb.createFont(); //font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 14); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字体应用到当前的样式 style.setFont(font); return style; } /** * 保存文件 * @param wk * @param title * @param url */ public void SaveFile(HSSFWorkbook wb,String title,File url) { try{ FileOutputStream fout=new FileOutputStream(""+url+"/"+title+".xls"); wb.write(fout); fout.close(); wb.removeSheetAt(0); }catch(Exception e){ System.out.println(e); } }}