public static String export() {
//生成xls的位置,要在webapps下,下载时才能访问的到
final String exportPath = "D:\\OnlineJudge\\tomcat_normal\\webapps\\contestForxls\\";
// 添加标题
List<String> title = new ArrayList<String>();
title.add("month");
title.add("money");
OutputStream os = null;
// 输出的excel的路径
String filePath = exportPath + "test.xls";
try {
//如果文件夹不存在就创建
File baseFile = new File(exportPath);
if (!baseFile.exists()) {
baseFile.createNewFile();
}
//如果文件夹存在就删除
File exportFile = new File(filePath);
if (exportFile.exists()) {
exportFile.delete();
}
// Excel单元格的一些样式
WritableCellFormat wcCenter = new WritableCellFormat();
wcCenter.setAlignment(Alignment.CENTRE);
WritableCellFormat wcCenterRed = new WritableCellFormat();
wcCenterRed.setAlignment(Alignment.CENTRE);
wcCenterRed.setBorder(Border.ALL, BorderLineStyle.THIN);
wcCenterRed.setBackground(jxl.format.Colour.RED);
WritableCellFormat wcCenterGreen = new WritableCellFormat();
wcCenterGreen.setAlignment(Alignment.CENTRE);
wcCenterGreen.setBorder(Border.ALL, BorderLineStyle.THIN);
wcCenterGreen.setBackground(jxl.format.Colour.GREEN);
// 创建Excel工作薄
WritableWorkbook wwb;
// 新建立一个jxl文件,即生成.xls文件
os = new FileOutputStream(filePath);
wwb = Workbook.createWorkbook(os);
// 添加第一个工作表并设置第一个Sheet的名字
WritableSheet sheet = wwb.createSheet("test", 0);
Label label;
for (int i = 0; i < title.size(); i++) {
// Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z
// 在Label对象的子对象中指明单元格的位置和内容
label = new Label(i, 0, title.get(i), wcCenter);
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
}
// 下面往xls表格里面填充数据,是一行一行的添加
int row = 1;// 行,第0行给标题占用了
//第一行
int col = 0;// 列
label = new Label(col++, row, "January", wcCenter);
sheet.addCell(label);
label = new Label(col++, row, "10000", wcCenter);
sheet.addCell(label);
//第二行
row++;
col = 0;// 列
label = new Label(col++, row, "February", wcCenter);
sheet.addCell(label);
label = new Label(col++, row, "8000", wcCenter);
sheet.addCell(label);
// 写入数据
wwb.write();
// 关闭文件
wwb.close();
int index = filePath.lastIndexOf('\\');
if (index != -1) {
filePath = filePath.substring(index + 1);
}
return filePath;
} catch (Exception e) {
System.out.println("导出错误!");
e.printStackTrace();
// return "导出错误!";
return null;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}