过时方法示例:
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFCellStyle style = wb.createCellStyle(); // 样式对象
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
/**字体begin*/
style.setFillForegroundColor(HSSFColor.SKY_BLUE.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.BLACK.index);//HSSFColor.VIOLET.index //字体颜色
font.setFontHeightInPoints((short)12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //字体增粗
//把字体应用到当前的样式
style.setFont(font);
/**字体end*/
HSSFRow row = sheet.createRow((short) 0);
HSSFRow row2 = sheet.createRow((short) 1);
新方法示例:
// 单元格格式
CellStyle cellStyle = excel.createCellStyle();
cellStyle.setRotation((short) 255);// 文字竖排列
cellStyle.setAlignment(HorizontalAlignment.CENTER);// 左右居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
// 单元格格式
CellStyle cellStyle2 = excel.createCellStyle();
cellStyle2.setWrapText(true);// 文字自动换行
cellStyle2.setVerticalAlignment(VerticalAlignment.TOP);// 向上对齐
// 单元格格式
Font font = excel.createFont();
font.setColor(IndexedColors.BLUE.getIndex());
font.setFontName("宋体");
CellStyle cellStyle3 = excel.createCellStyle();
cellStyle3.setAlignment(HorizontalAlignment.CENTER);// 左右居中
cellStyle3.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中
cellStyle3.setFont(font);
插入图片的示例:
/**
* 插入图片到Excel.
* @param dirName
* @param excel
*/
private void insertPics(String dirName, Workbook excel) throws Exception {
File dir = new File(dirName);
FileInputStream[] input = null;
try {
File[] listFiles = dir.listFiles();
int len = listFiles.length;
input = new FileInputStream[len];
for (int i = 0; i < len; i++) {
Sheet sheet = excel.createSheet("图片" + (i + 1));
input[i] = new FileInputStream(listFiles[i]);
int pictureIdx = excel.addPicture(IOUtils.toByteArray(input[i]), Workbook.PICTURE_TYPE_PNG);
// 图片插入坐标
ClientAnchor anchor = excel.getCreationHelper().createClientAnchor();
anchor.setCol1(0);
anchor.setRow1(1);
// 插入图片
sheet.createDrawingPatriarch().createPicture(anchor, pictureIdx).resize();
}
} catch (FileNotFoundException e) {
throw new RuntimeException("向Excel插入图片时未找到目标图片", e);
} catch (IOException e) {
throw new RuntimeException("向Excel插入图片失败", e);
} finally {
if (input != null) {
input.close();
}
}
}