这几天在写论文实验的时候,需要对比不同算法的不同指标,然后需要将每个实验跑出来的结果放在一个文档里面,进行对比,之前是每个实验放在独立的文件当中,现在全部放在一起,对比更加直观。
private static int index = 1 ; private static WritableWorkbook book = null; private static WritableSheet sheet = null; private static void writeExcel(String sheetname,List<Double> bill, List<Double> cpltRt, List<Double> avgECost, int devicenum) { try { String testName = sheetname; sheetname = "summary"; File file = new File(sheetname+".xls"); int baseRow = (index-1)*6; Number[][] numbers = new Number[4][bill.size()]; if(index==1) { file.delete(); } if(!file.exists()) { book = Workbook.createWorkbook(file); sheet = book.createSheet(sheetname, 0) ; Label testLabel = new Label(0,baseRow,testName); sheet.addCell(testLabel); for(int i=0;i<bill.size();i++) { numbers[0][i] = new Number(i,baseRow+1,(i+1)*Parameters.Task_Inc_Step); numbers[1][i] = new Number(i,baseRow+2,bill.get(i)); numbers[2][i] = new Number(i,baseRow+3,cpltRt.get(i)); numbers[3][i] = new Number(i,baseRow+4,avgECost.get(i)); sheet.addCell(numbers[0][i]); sheet.addCell(numbers[1][i]); sheet.addCell(numbers[2][i]); sheet.addCell(numbers[3][i]); } book.write(); book.close(); } else { Workbook wb = Workbook.getWorkbook(file); File tempfile = new File("tempfile.xls"); WritableWorkbook wwb = Workbook.createWorkbook(tempfile, wb); WritableSheet ws = wwb.getSheet(0); Label testLabel = new Label(0,baseRow,testName); ws.addCell(testLabel); for(int i=0;i<bill.size();i++) { numbers[0][i] = new Number(i,baseRow+1,(i+1)*Parameters.Task_Inc_Step); numbers[1][i] = new Number(i,baseRow+2,bill.get(i)); numbers[2][i] = new Number(i,baseRow+3,cpltRt.get(i)); numbers[3][i] = new Number(i,baseRow+4,avgECost.get(i)); ws.addCell(numbers[0][i]); ws.addCell(numbers[1][i]); ws.addCell(numbers[2][i]); ws.addCell(numbers[3][i]); } wwb.write(); wwb.close(); wb.close(); file.delete(); tempfile.renameTo(file); } index ++; } catch (Exception e) { e.printStackTrace(); } }
简单说一下算法的思路,第一次写入的时候,用WritableWorkbook WritableSheet 新建,后来,使用之前的已经写入的文件,创建一个新文件,最后,将文件改名。