Excel2003:
HSSFWorkbook workbook = new HSSFWorkbook();// excel文件对象
HSSFSheet sheet = workbook.createSheet("测试");// 工作表对象
sheet.setColumnWidth(0, 3000);//设置列宽
// 设置表头的样式
HSSFFont headfont = workbook.createFont();
headfont.setFontName("Times New Roman"); //字体格式
headfont.setFontHeightInPoints((short) 9);// 字体大小
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 加粗
HSSFCellStyle headstyle = workbook.createCellStyle();
headstyle.setFont(headfont);
headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
headstyle.setLocked(true); //是否锁定单元格
headstyle.setWrapText(true);// 自动换行
//设置单元格百分比样式
HSSFCellStyle cellStyleRatio = workbook.createCellStyle();
cellStyleRatio.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00%"));
//设置单元格货币样式
HSSFCellStyle cellMoneyStyle = workbook.createCellStyle();
HSSFDataFormat format= workbook.createDataFormat();
cellMoneyStyle.setDataFormat(format.getFormat("#,##0"));
//设置单元格小数格式
HSSFCellStyle cellFlotStyle = workbook.createCellStyle();
cellFlotStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
excel2007:
XSSFWorkbook workbook = new XSSFWorkbook();// excel文件对象
XSSFSheet sheet = workbook.createSheet("测试");// 工作表对象
//设置列宽
sheet.setColumnWidth(0, 3000);
XSSFFont headfont = workbook.createFont();
headfont.setFontName("Times New Roman");
headfont.setFontHeightInPoints((short) 9);// 字体大小
headfont.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);// 加粗
XSSFCellStyle headstyle = workbook.createCellStyle();
headstyle.setFont(headfont);
headstyle.setAlignment(HorizontalAlignment.CENTER);// 左右居中
headstyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
headstyle.setBorderTop(XSSFCellStyle.BORDER_THIN); //设置上边框
headstyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); //设置下边框
headstyle.setBorderLeft(XSSFCellStyle.BORDER_THIN); //设置做边框
headstyle.setBorderRight(XSSFCellStyle.BORDER_THIN); //设置右边框
headstyle.setLocked(true);
headstyle.setWrapText(true);// 自动换行
XSSFCellStyle cellStyleRatio = workbook.createCellStyle();
XSSFDataFormat fmt = workbook.createDataFormat();
cellStyleRatio.setDataFormat(fmt.getFormat("0.00%"));//设置百分比样式
cellStyleRatio.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); //设置单元格背景颜色
cellStyleRatio.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);