使用jxl,把多个csv(文件名相同,目录不同)转换到同一个excel中,并求平均值

/**
 * 把多个csv(文件名相同,目录不同)转换到一个excel中,并求平均值
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import jxl.Cell;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/*
 * 需要设置的两个参数是valueFactor、path
 */
public class CSVN2Exc {
    public static void main(String args[]) {
        int factor=1;//单位转化
         String path="C:/Documents and Settings/Administrator/桌面/shareArray_Michael";//绝对路径名
         //String path = "D:/MyWorkplace/CSV2Excel";
        String resultPath = path + "/deal";//输出结果目录
        File resultDir = new File(resultPath);
        if (!resultDir.exists())
            resultDir.mkdir();
        findFile(path, resultPath);
        
        File files[]=resultDir.listFiles();
        for(File f:files){
            avgValue(f,factor);
        }
        System.out.println("convert successfully!");
    }

    /*
     * 处理目录下的所有.csv文件
     */
    private static void findFile(String filepath, String resultPath) {
        File f = new File(filepath);// 定义文件路径
        if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
            if (f.listFiles().length == 0) {// 若目录下没有文件则无操作
                ; // do nothing
            } else {// 若有则把文件放进数组,并判断是否有下级目录
                File files[] = f.listFiles();
                int i = f.listFiles().length;
                for (int j = 0; j < i; j++) {
                    if (files[j].isDirectory()) {
                        findFile(files[j].getAbsolutePath(), resultPath);// 递归调用del方法并取得子目录路径
                    } else {
                        String name = files[j].getName();
                        if (name.endsWith(".csv")) {
                            convert(files[j], resultPath);
                        }
                    }
                }
            }
        }
    }
    
    /*
     * 把。csv转化为.xls
     */
    private static void convert(File file, String resultPath) {
        FileReader reader;
        String CSVName = file.getAbsolutePath();
        try {
            String filename=file.getName().substring(0,file.getName().lastIndexOf("."));
            String resultName = resultPath + "/" + filename + ".xls";//结果文件名
            WritableWorkbook book;
            File resultFile = new File(resultName);
            if (!resultFile.exists()) {
                book = Workbook.createWorkbook(resultFile);
            } else {
                // Excel获得文件
                Workbook wb = Workbook.getWorkbook(new File(resultName));
                // 打开一个文件的副本,并且指定数据写回到原文件
                book = Workbook.createWorkbook(new File(resultName), wb);
            }

            int num = book.getNumberOfSheets();
            WritableSheet sheet = book.createSheet("t" + (num+1), num);
            // 读CSV文件
            reader = new FileReader(CSVName);
            BufferedReader br = new BufferedReader(reader);
            int i = 0, j = 0;
            String s = null;
            while ((s = br.readLine()) != null) {
                if (s.trim().length() > 1) {
                    String[] p = s.split(" ");
                    for (j = 0; j < p.length; j++) {
                        if (i == 0) {
                            // 将p[j]加入到excel中
                            Label label = new Label(j, i, p[j]);
                            // 将定义好的单元格添加到工作表中
                            sheet.addCell(label);
                        } else {
                            int value = Integer.valueOf(p[j]);
                            jxl.write.Number number = new jxl.write.Number(j,
                                    i, value);
                            sheet.addCell(number);
                        }
                    }
                }
                i++;
            }
            br.close();
            reader.close();

            // 写入数据并关闭文件
            book.write();
            book.close();

        } catch (FileNotFoundException e) {
            System.err.println("\"" + CSVName
                    + "\" is not found! Using default parameters!");
        } catch (IOException e) {
            System.err.println("IO occurr an error!");
        } catch (Exception e) {
            System.err.println("\"" + CSVName);
        }
    }
    
    /*
     * 求平均值
     */
    private static void avgValue(File file,int factor){
        try {
            // Excel获得文件
            Workbook wb = Workbook.getWorkbook(file);
            // 打开一个文件的副本,并且指定数据写回到原文件
            WritableWorkbook book = Workbook.createWorkbook(file, wb);
            
            int i=0,j=0,k=0;
            int num=book.getNumberOfSheets();
            
            WritableSheet []sheet=new WritableSheet[num+1];
            sheet[num] = book.createSheet("平均值"+(num+1), num);
            for(i=0;i<num;i++){
                sheet[i]=book.getSheet(i);
            }
            
            Cell cell;
            for(i=0;i<sheet[0].getRows();i++){
                for(j=0;j<sheet[0].getColumns();j++){
                    //目录行
                    if(i==0){
                        Label label=new Label(j,i,sheet[0].getCell(j,i).getContents());
                        sheet[num].addCell(label);
                    }
                    //数据
                    else{
                        //计算平均值
                        int sum=0;
                        for(k=0;k<num;k++){
                            cell=sheet[k].getCell(j,i);
                            sum+=Integer.valueOf(cell.getContents());
                        }
                        
                        jxl.write.Number number = new jxl.write.Number(j,
                                i, sum/num/factor);
                        sheet[num].addCell(number);
                        
                    }
                }
            }
            // 写入数据并关闭文件
            book.write();
            book.close();
            
        } catch (BiffException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("error");
        }
    }
}

posted on 2012-04-28 10:36  stronger  阅读(1105)  评论(0)    收藏  举报

导航