public static void main(String[] args) throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
//创建一个工作表可设置名字
HSSFSheet sheet = wb.createSheet();
// HSSFSheet sheet = wb.createSheet("测试");
// 设置字体
HSSFFont font = wb.createFont();
//设置字体
// font.setFontName("仿宋_GB2312");
//设置字体颜色
font.setColor(HSSFColor.WHITE.index);//字体为白色
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体大小
font.setFontHeightInPoints((short) 12);
// 设置样式
HSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setFont(font);
cellStyle.setFillForegroundColor(HSSFColor.DARK_TEAL.index);// 设置背景色
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//居中
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFCellStyle cellStyle2 = wb.createCellStyle();
//设置自动换行
cellStyle2.setWrapText(true);
//设置垂直居中
cellStyle2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFCellStyle cellStyle3 = wb.createCellStyle();
//设置垂直居中
cellStyle3.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//设置居中
cellStyle3.setAlignment(HSSFCellStyle.ALIGN_CENTER);
int CountColumnNum = 4;//设置列数
HSSFRow firstrow = sheet.createRow(0); //表格第一行(从0开始)
HSSFCell[] firstcell = new HSSFCell[CountColumnNum];
String[] names = new String[CountColumnNum];
names[0] ="System Test Interface";
names[1] ="Input";
names[2] ="Output";
names[3] ="Result";
for(int i= 0 ;i < CountColumnNum ;i++){
firstcell[i] = firstrow.createCell(i);
firstcell[i].setCellStyle(cellStyle);
firstcell[i].setCellValue(new HSSFRichTextString(names[i]));
}
String aa = "qwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnmqwertyuiopasdfghjklzxcvbnm";
// 创建电子表格的一行
HSSFRow row = sheet.createRow(1); //表格第二行
// 在一行内循环
HSSFCell cell = row.createCell(0);
cell.setCellStyle(cellStyle3);
cell.setCellValue(new HSSFRichTextString("qa"));
cell = row.createCell(1);
cell.setCellStyle(cellStyle2);
cell.setCellValue(new HSSFRichTextString(aa));
cell = row.createCell(2);
cell.setCellStyle(cellStyle2);
cell.setCellValue(new HSSFRichTextString(aa));
cell = row.createCell(3);
cell.setCellStyle(cellStyle3);
cell.setCellValue(new HSSFRichTextString("qa"));
//设置自适应列宽度
sheet.autoSizeColumn(0);
sheet.setColumnWidth(1,10500);//第一个参数代表列id(从0开始),第2个参数代表宽度值
sheet.setColumnWidth(2,10500);
sheet.autoSizeColumn(3);
//创建文件输出流,创建电子表格
OutputStream out = new FileOutputStream("E:\\automationtest.xls");
wb.write(out);
out.close();
System.out.println("excel创建成功") ;
}
转载于:https://my.oschina.net/sunchm/blog/1589691