将数组插入Excel

时间:2014-05-23 16:35:28

标签: java arrays excel jxl jexcelapi

我有一个数组,我想从中检索值并使用Jxl将它们插入到excel中,将一个值放入一行,例如:

1| blah blah blah

2| blah blah blah

3| blah blah blah

我可以检索数组中的值,如下面的代码所示,但是将它们插入行对我来说很难....我通过各种尝试管理的最好的是插入正确的行数但是所有具有相同值(存储在数组中的最后一个值)。

private static void InsertStrings() throws RowsExceededException, WriteException {
    try {
        System.out.println("Starting Write to Excel");
        WritableWorkbook workbook = Workbook.createWorkbook(new File("C:\\Users\\Jason\\Documents\\Development\\Seaport Crawler\\CrawlerResults.xls"));

        WritableSheet sheet = workbook.createSheet("Results", 0);
        Label label = new Label(0, 0, "Notices to Mariners"); 
        sheet.addCell(label);
        for ( int indx = 0; indx < arr_Heading.size(); indx++)
        {
            /********HEADING and TITLE ARRAY*********/
            String heading;
            int rowValue = indx;            
            heading = arr_Heading.get(rowValue);    

            //Editing the Descriptions
            if (heading.contains("-")) {
                // Split it
                String string = heading;
                String[] parts = string.split("-",2);
                String part1 = parts[0]; // Heading
                String part2 = parts[1]; // Title
                //String part1s = part1.replaceAll("\\s+","");//Replace Spaces with none
                // String part2s = part2.replaceAll("\\s+","");

                System.out.println("row Value........" + rowValue + " Heading... " + part1 + " Title... " + part2);

                //Insert Strings to Excel Workbook
                Label ntmHeading = new Label(2, indx, part1);
                sheet.addCell(ntmHeading);

            }else{
                //something
            }
            // All sheets and cells added. Now write out the workbook 
            workbook.write(); 
            workbook.close();
        }
    } catch (IOException e) {
        System.out.println("WRITE TO EXCEL FAILED");
        e.printStackTrace();
    }

谢谢

1 个答案:

答案 0 :(得分:1)

在for循环之外写下以下语句:

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

对try catch block / throws做一些调整,然后就可以了。