/** * 创建Excel文件 * @param orderList * @throws Exception */ public static void createExecl() throws Exception { // 文件名 String fileName = "D:\\AR.xls"; // 文件输出流 FileOutputStream out = new FileOutputStream(fileName); // 创建工作簿 HSSFWorkbook wb = new HSSFWorkbook(); // 创建工作表 HSSFSheet sheet = wb.createSheet("sheet1"); // 创建行和列 HSSFCell cell = null; HSSFRow row = null; // 创建一个单元的样式 HSSFCellStyle style = wb.createCellStyle(); // 设置单元样式 setCellStyle(style); // 创建字体样式 HSSFFont font = wb.createFont(); font.setFontName("黑体"); font.setFontHeightInPoints((short) 22); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 标题行 String[] headRow1 = {"序号", "学校","", "班级信息","","个人信息","","", "综合考评"}; String[] headRow2 = {"", "名称", "位置", "年级", "几班", "姓名", "性别", "联系方式", ""}; int rowint = 0; int titlerow1 = rowint++; // 创建标题行 row = sheet.createRow(titlerow1); for (int i=0; i<headRow1.length; i++) { cell = row.createCell(i); cell.setCellValue(headRow1[i]); cell.setCellStyle(style); } int titlerow2 = rowint++; row = sheet.createRow(titlerow2); // 创建标题行 for (int i = 0; i < headRow2.length; i++) { cell = row.createCell(i); cell.setCellValue(headRow2[i]); cell.setCellStyle(style); } // 合并单元格 sheet.addMergedRegion(new CellRangeAddress(titlerow1, titlerow1, 1, 2)); // 合并第一行 // 2,三两格,从0开始 sheet.addMergedRegion(new CellRangeAddress(titlerow1, titlerow1, 3, 4)); sheet.addMergedRegion(new CellRangeAddress(titlerow1, titlerow1, 5, 7)); sheet.addMergedRegion(new CellRangeAddress(titlerow1, titlerow2, 8, 8)); // 设置每列的宽度 int k = 0; sheet.setColumnWidth(k++, 4200); sheet.setColumnWidth(k++, 4200); sheet.setColumnWidth(k++, 4200); sheet.setColumnWidth(k++, 4200); sheet.setColumnWidth(k++, 4200); sheet.setColumnWidth(k++, 4200); sheet.setColumnWidth(k++, 4200); sheet.setColumnWidth(k++, 4200); // 放入信息,一般为list,这里用模拟信息 String[] message = {"1","清华","北京","计算机","1","snow","女","562771681","有"}; row = sheet.createRow(rowint); for (int i = 0; i < message.length; i++) { cell=row.createCell(i); cell.setCellStyle(style); cell.setCellValue((message[i])); } wb.write(out); out.close(); }
/** * 设置单元样式 * @param style */ private static void setCellStyle(HSSFCellStyle style) { // 背景色的设定 style.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index); // 前景色的设定 style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); // 填充模式 style.setFillPattern(HSSFCellStyle.FINE_DOTS); // 设置水平居中 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 上下居中 style.setVerticalAlignment(HSSFCellStyle.ALIGN_CENTER); // 设置上下左右边框样式 style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); }