在jExcel API中创建多个工作表

时间:2013-01-11 23:47:11

标签: java excel jexcelapi

如果一个工作表已满jExcel API,我需要使用(65536 rows)在Java中创建多个Excel工作表。假设如果一张纸已满,则在下一张纸中,它应该从第一张纸中停止的位置开始自动写入。当一张纸已满时,我只是坚持使用逻辑来动态创建它。下面是我到目前为止所做的代码。

public void write() throws IOException, WriteException {
    File file = new File(inputFile);
    WorkbookSettings wbSettings = new WorkbookSettings();

    wbSettings.setLocale(new Locale("en", "EN"));

    WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);

    writingToExcel(workbook);
}


//Logic to create sheet dyanmically if one is full should be done here I guess?
private void writingToExcel(WritableWorkbook workbook) {

    workbook.createSheet("Report", 0);
    WritableSheet excelSheet = workbook.getSheet(0);
    try {
        createLabel(excelSheet);
        createContent(excelSheet);
    } catch (WriteException e) {
        e.printStackTrace();
    } finally {
        try {
            workbook.write();
            workbook.close();   
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }

    }
}

private void createLabel(WritableSheet sheet) throws WriteException {

    WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
    times = new WritableCellFormat(times10pt);
    times.setWrap(true);

    WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false,UnderlineStyle.SINGLE);
    timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
    timesBoldUnderline.setWrap(true);

    CellView cv = new CellView();
    cv.setFormat(times);
    cv.setFormat(timesBoldUnderline);
    cv.setAutosize(true);

    // Write a few headers
    addCaption(sheet, 0, 0, "Header 1");
    addCaption(sheet, 1, 0, "This is another header");

}

private void createContent(WritableSheet sheet) throws WriteException,
        RowsExceededException {

    for (int i = 1; i < 70000; i++) {
        addNumber(sheet, 0, i, i + 10);
        addNumber(sheet, 1, i, i * i);
    }
}

private void addCaption(WritableSheet sheet, int column, int row, String s)
        throws RowsExceededException, WriteException {
    Label label;
    label = new Label(column, row, s, timesBoldUnderline);
    sheet.addCell(label);
}

private void addNumber(WritableSheet sheet, int column, int row,
        Integer integer) throws WriteException, RowsExceededException {
    Number number;
    number = new Number(column, row, integer, times);
    sheet.addCell(number);
}

我不确定如何在我的代码中添加该逻辑。

任何建议都会有很大帮助吗?

或者在任何情况下,任何人都可以为我提供一个简单的例子,如果一张纸已满,它应该开始自动写入不同的纸张(第二张)?

2 个答案:

答案 0 :(得分:4)

我对以下两种方法进行了更改: -

private void writingToExcel(WritableWorkbook workbook) {
    try {
        // don't create a sheet now, instead, pass it in the workbook
        createContent(workbook);
    }
    catch (WriteException e) {
        e.printStackTrace();
    }
    finally {
        try {
            workbook.write();
            workbook.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (WriteException e) {
            e.printStackTrace();
        }

    }
}

// instead of taking a sheet, take a workbook because we cannot ensure if the sheet can fit all the content at this point
private void createContent(WritableWorkbook workbook) throws WriteException {

    int excelSheetIndex = 0;
    int rowIndex = 0;
    WritableSheet excelSheet = null;

    for (int i = 1; i < 70000; i++) {

        // if the sheet has hit the cap, then create a new sheet, new label row and reset the row count
        if (excelSheet == null || excelSheet.getRows() == 65536) {
            excelSheet = workbook.createSheet("Report " + excelSheetIndex, excelSheetIndex++);
            createLabel(excelSheet);
            rowIndex = 0;
        }

        // instead of using i for row, use rowIndex
        addNumber(excelSheet, 0, rowIndex, i + 10);
        addNumber(excelSheet, 1, rowIndex, i * i);

        // increment the sheet row
        rowIndex++;
    }
}

答案 1 :(得分:0)

公共课DscMigration {

private WritableCellFormat timesBoldUnderline;
private WritableCellFormat times;
private String inputFile;

public void setOutputFile(String inputFile) {
    this.inputFile = inputFile;
}

public void write() throws IOException, WriteException {
    File file = new File(inputFile);
    WorkbookSettings wbSettings = new WorkbookSettings();

    wbSettings.setLocale(new Locale("en", "EN"));

    WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings);
    workbook.createSheet("Report", 0);
    WritableSheet excelSheet = workbook.getSheet(0);
    createLabel(excelSheet);
    createContent(excelSheet);

    workbook.write();
    workbook.close();
}

private void createLabel(WritableSheet sheet) throws WriteException {
    // Lets create a times font
    WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10);
    // Define the cell format
    times = new WritableCellFormat(times10pt);
    // Lets automatically wrap the cells
    times.setWrap(true);

    // Create create a bold font with unterlines
    WritableFont times10ptBoldUnderline = new WritableFont(
            WritableFont.TIMES, 10, WritableFont.BOLD, false,
            UnderlineStyle.SINGLE);
    timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline);
    // Lets automatically wrap the cells
    timesBoldUnderline.setWrap(true);

    CellView cv = new CellView();
    cv.setFormat(times);
    // cv.setFormat(timesBoldUnderline);
    // cv.setFormat(cf)
    cv.setAutosize(true);

    // Write a few headers
    addCaption(sheet, 0, 0, "COM_ID");
    addCaption(sheet, 1, 0, "OBJECTID");
    addCaption(sheet, 2, 0, "GNOSISID");

}

private void createContent(WritableSheet sheet) throws WriteException,
        RowsExceededException {

    /**
     * Create a new instance for cellDataList
     */
    List<DataObj> cellDataListA = new ArrayList<DataObj>();
    List<DataObj> nonDuplicateA = new ArrayList<DataObj>();
    List<DataObj2> cellDataListB = new ArrayList<DataObj2>();
    List<DataObj2> nonDuplicateB = new ArrayList<DataObj2>();
    List<DataObj> nonDuplicateAB = new ArrayList<DataObj>();
    List<DataObj> misMatchAB = new ArrayList<DataObj>();
    List<DataObj> copyA = new ArrayList<DataObj>();
    List<DataObj2> comID = new ArrayList<DataObj2>();

    try {
        /**
         * Create a new instance for FileInputStream class
         */
        // input1--> col1 -livelink id ; col2->livlink filename; col3-> gnosis id; col4-> filename
        FileInputStream fileInputStream = new FileInputStream(
                "C:/Documents and Settings/nithya/Desktop/DSC/Report/input1.xls");
    //input2 --> col1 comid all, col2 -> object id for common
        FileInputStream fileInputStream2 = new FileInputStream(
        "C:/Documents and Settings/nithya/Desktop/DSC/Report/input2.xls");

        /**
         * Create a new instance for POIFSFileSystem class
         */
        POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
        POIFSFileSystem fsFileSystem2 = new POIFSFileSystem(fileInputStream2);
        /*
         * Create a new instance for HSSFWorkBook Class
         */
        HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
        HSSFSheet hssfSheet = workBook.getSheetAt(0);
        HSSFWorkbook workBook2 = new HSSFWorkbook(fsFileSystem2);
        HSSFSheet hssfSheet2 = workBook2.getSheetAt(0);
        /**
         * Iterate the rows and cells of the spreadsheet to get all the
         * datas.
         */
        Iterator rowIterator = hssfSheet.rowIterator();
        Iterator rowIterator2 = hssfSheet2.rowIterator();
        while (rowIterator.hasNext()) {
            HSSFRow hssfRow = (HSSFRow) rowIterator.next();

            if ((hssfRow.getCell((short) 0) != null)
                    && (hssfRow.getCell((short) 1) != null)) {
                cellDataListA.add(new DataObj(hssfRow.getCell((short) 0)
                        .toString().trim(), hssfRow.getCell((short) 1)
                        .toString().trim()));
            }

            if ((hssfRow.getCell((short) 2) != null)
                    && (hssfRow.getCell((short) 3) != null)) {
                cellDataListB.add(new DataObj2(hssfRow.getCell((short) 2)
                        .toString().trim(), hssfRow.getCell((short) 3)
                        .toString().trim()));
            }

        }
        // Replace Duplicate in Livelink Startd
        Set set = new HashSet();
        List newList = new ArrayList();
        nonDuplicateA.addAll(cellDataListA);
        for (int i = 0; i < nonDuplicateA.size(); i++) {
            DataObj b = nonDuplicateA.get(i);
            if (set.add(b.getCol1()))
                newList.add(nonDuplicateA.get(i));
        }

        nonDuplicateA.clear();
        nonDuplicateA.addAll(newList);
        for (int i = 0; i < nonDuplicateA.size(); i++) {
            DataObj a = nonDuplicateA.get(i);
        }
        System.out.println("nonDuplicateA=="+nonDuplicateA.size());
        // Replace Duplicate in Livelink End

        // Replace Duplicate in Gnosis Startd
        Set set2 = new HashSet();
        List newList2 = new ArrayList();
        System.out.println("cellDataListB=="+cellDataListB.size());
        nonDuplicateB.addAll(cellDataListB);
        for (int i = 0; i < nonDuplicateB.size(); i++) {
            DataObj2 b = nonDuplicateB.get(i);
                if (set2.add(b.getCol1()))
                newList2.add(nonDuplicateB.get(i));
        }

        nonDuplicateB.clear();
        nonDuplicateB.addAll(newList2);

        System.out.println("nonDuplicateB=="+nonDuplicateB.size());
        // Replace Duplicate in Gnosis End

        // Common record
        //System.out.println("------Common----");
        for (int i = 0; i < nonDuplicateA.size(); i++) {
            DataObj a = nonDuplicateA.get(i);
            for (int j = 0; j < nonDuplicateB.size(); j++) {
                DataObj2 b = nonDuplicateB.get(j);

                    if((a.getCol2()!=null && b.getCol2()!=null )){
                        //System.out.println("---------");
                if (a.getCol2().equalsIgnoreCase(b.getCol2())) {

                //  System.out.println(a.getCol2() +"--"+i+"--"+b.getCol2());
                    nonDuplicateAB.add(new DataObj(a.getCol1().toString()
                            .trim(), b.getCol1().toString().trim()));
                    //addLabel(sheet, 0, i, a.getCol1().toString().trim());
                    // addLabel(sheet, 1, i, b.getCol1().toString().trim());
                    break;
                }


            }

            }

        }
        System.out.println("nonDuplicateAB=="+nonDuplicateAB.size());
        TreeMap misA = new TreeMap();
        //System.out.println("------Missing----");
        for (int i = 0; i < nonDuplicateA.size(); i++) {
            DataObj a = nonDuplicateA.get(i);
            for (int j = 0; j < nonDuplicateB.size(); j++) {
                DataObj2 b = nonDuplicateB.get(j);
                    if((a.getCol2()!=null && b.getCol2()!=null )){
                    if (!(a.getCol2().equals(b.getCol2()))) {
                    //System.out.println(a.getCol1() +"="+b.getCol1());

                    //break;

                    if(misA.containsValue(a.getCol2())){
                        misA.remove(a.getCol1());
                    }
                    else
                    {
                        misA.put(a.getCol1(), a.getCol2());
                    }
                }

            }

            }
        }
        //System.out.println("SIze mis="+misA);
        TreeMap misB = new TreeMap();

        for (int i = 0; i < nonDuplicateB.size(); i++) {
            DataObj2 a = nonDuplicateB.get(i);
            for (int j = 0; j < nonDuplicateA.size(); j++) {
                DataObj b = nonDuplicateA.get(j);
                    if((a.getCol2()!=null && b.getCol2()!=null )){
                    if (!(a.getCol2().equals(b.getCol2()))) {
                    //System.out.println(a.getCol1() +"="+b.getCol1());


                    if(misB.containsValue(a.getCol2())){
                        misB.remove(a.getCol1());
                    }
                    else
                    {
                        misB.put(a.getCol1(), a.getCol2());
                    }
                }

            }

            }
        }
    //  System.out.println("SIze misB="+misB);
        //Getting ComID and Object Id from excel start
        while (rowIterator2.hasNext()) {

            HSSFRow hssfRow2 = (HSSFRow) rowIterator2.next();

            if ((hssfRow2.getCell((short) 0) != null)
                    && (hssfRow2.getCell((short) 1) != null)) {
                comID.add(new DataObj2(hssfRow2.getCell((short) 0)
                        .toString().trim(), hssfRow2.getCell((short) 1)
                        .toString().trim()));
            }
        }
        System.out.println("Size ComID="+comID.size());
        TreeMap hm = new TreeMap(); 
        System.out.println("Please wait...Data comparison.. ");
        for (int i = 0; i < nonDuplicateAB.size(); i++) {
            DataObj a = nonDuplicateAB.get(i);
            for(int j=0;j<comID.size();j++ ){
                DataObj2 b = comID.get(j);
                //System.out.println((b.getCol2()+"---"+a.getCol1()));

                if(b.getCol2().equalsIgnoreCase(a.getCol1())){
                    hm.put(b.getCol1(), b.getCol2());
                    break;
                }
            }
        }
        System.out.println("Size HM="+hm.size());
        //Getting ComID and Object Id from excel End

        //Data Base Updation
        Connection conn = null;
        try {

            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                       conn =   DriverManager.getConnection(
                      "jdbc:oracle:thin:@cxxxxx:5487:dev", "",
                      "");

        System.out.println("after calling conn");

                Set set6 = hm.entrySet(); 
                Iterator i = set6.iterator(); 
                String gnosisNodeId="";
                int update=1;
                while(i.hasNext()) { 
                Map.Entry me = (Map.Entry)i.next(); 
                //System.out.print(me.getKey() + ": "); 
                //System.out.println(me.getValue()); 
        //  System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
                for(int m=0;m<nonDuplicateAB.size();m++){
                    DataObj a = nonDuplicateAB.get(m);
                    if(me.getValue().toString().equalsIgnoreCase(a.getCol1())){
                    gnosisNodeId=a.getCol2().toString();
                    nonDuplicateAB.remove(m);
                    break;
                    }
                }
                //System.out.println("nonDuplicateAB="+nonDuplicateAB.size());
                if(gnosisNodeId!=null){
                    //System.out.println("LOOP");
                String s1="UPDATE component SET com_xml =  UPDATEXML(com_xml, '*/url/value/text()', '";
                String s2="http://dmfwebtop65.pfizer.com/webtop/drl/objectId/"+gnosisNodeId;
                String s3="') where com_id="+me.getKey().toString().substring(1)+"";
                Statement   stmt1=null;
                //http://dmfwebtop65.pfizer.com/webtop/drl/objectId/0901201b8239cefb
                    try {
                        String updateString1 = s1+s2+s3; 
                        stmt1 = conn.createStatement();

                        int rows =stmt1.executeUpdate(updateString1);
                 if (rows>0) {
                     addLabel(sheet, 0, update, me.getKey().toString().substring(1));
                        addLabel(sheet, 1, update, me.getValue().toString().substring(1));
                        addLabel(sheet, 2, update,gnosisNodeId );
                        update++;   
                    System.out.println("Update Success="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
                 }
                 else
                 {
                 System.out.println("Not Updated="+me.getKey().toString().substring(1)+ "-->" +me.getValue().toString().substring(1));
                 }

                    } catch (SQLException e) {
                        System.out.println("No Connect" + e);
                            } catch (Exception e) {
                            System.out.println("Error "+e.getMessage());
                        } 
                }
                else{System.out.println("No gnosis id found for ObjectID="+me.getKey().toString().substring(1)); }

            }//While 
        } //try
     catch (Exception e) {
        e.printStackTrace();
    }



}//Main try
     catch (Exception e) {
            e.printStackTrace();
        }
} //method

private void addCaption(WritableSheet sheet, int column, int row, String s)
        throws RowsExceededException, WriteException {
    Label label;
    label = new Label(column, row, s, timesBoldUnderline);
    sheet.addCell(label);
}

private void addNumber(WritableSheet sheet, int column, int row,
        Integer integer) throws WriteException, RowsExceededException {
    Number number;
    number = new Number(column, row, integer, times);
    sheet.addCell(number);
}

private void addLabel(WritableSheet sheet, int column, int row, String s)
        throws WriteException, RowsExceededException {
    Label label;
    label = new Label(column, row, s, times);
    sheet.addCell(label);
}

public static void main(String[] args) throws WriteException, IOException {
    DscMigration test = new DscMigration();
    test.setOutputFile("C:/Documents and Settings/nithya/Desktop/DSC/Report/Mapping.xls");
    test.write();
    System.out
            .println("Please check the result file under C:/Documents and Settings/nithya/Desktop/DSC/Report/Report.xls ");
}

} XXXX内部使用 基于WTTE-0043 ELC维护版本和错误修复计划模板 版本4.0生效日期:2010年7月1日 //错误修复计划

作者: 1个批准签名 目录 我撰写了这个可交付成果来记录执行维护版本或项目错误修复的计划。 名称日期 我编写了这个可交付成果来记录执行维护版本或错误修复XXX Plus v4.5的计划。 姓名日期

我批准此更改,并同意此记录代表执行维护版本或错误修复的准确完整计划,并完全支持此项目的实施,测试和发布活动。 名称日期 我已查看此记录的内容,发现它符合适用的BT合规要求。 姓名日期

签名 2简介 该项目可交付成果记录了所需的变更,计划方法,开发解决方案,测试计划,测试结果以及维护版本的发布批准或项目的错误修复。

3变更请求 请求者名称:

XX 宾语/ 系统名称:

项目 优先级(高/中/低):

高 变更申请号: NA 变更请求日期:

22-NOV-2011

问题描述或请求变更:

预计需要的开发时间:

1天(约)

4)4维护版本和错误修复方法 5开发解决方案 8支持参考 9修订历史