写项目到Excel单元格中 [英] Write items into excel cell

查看:253
本文介绍了写项目到Excel单元格中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是绝对新Eclipse的Java编码。我试图完成一个项目来管理库存。我有麻烦的地方在于,当我试图写的项目到Excel单元格中,我得到的错误说数组越界。

PS:项目和item.getPartname等是根据另一个类文件中的所有定义。
请帮忙。谢谢

 的FileOutputStream OS =新的FileOutputStream(orderreceipt);
            //创建将数据写入一个新的工作簿
            HSSFWorkbook WB2 =新HSSFWorkbook();
            //创建一个新的工作表:
            HSSFSheet newsheet = wb2.createSheet(MyNewSheet);
            //创建一个新行:            的for(int i = 0;我6;;我++){
                HSSFRow NEWROW = newsheet.createRow(ⅰ);
                sentorder项=(sentorder)items.get(ⅰ);
                为(短J = 0; J&小于5; J ++){
                    HSSFCell细胞= newrow.createCell(J);                    cell.setCellValue(item.getPartname());
                    cell.setCellValue(item.getPartnumber());
                    cell.setCellValue(item.getQuantity());
                    cell.setCellValue(新的Date());
                      HSSFCellStyle styleOfCell = wb2.createCellStyle();
                      styleOfCell.setDataFormat(HSSFDataFormat
                          .getBuiltinFormat(M / D / YY));
                      styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
                      styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
                      cell.setCellStyle(styleOfCell);                    }}
            wb2.write(OS);
    }


解决方案

我可以看到所附code不少问题:


  • 缺少文件扩展名当创建新的的FileOutputStream - 因为你生成的.xls工作簿,你可能想将其存储在XLS文件(扩展不会自动添加),也只是确保你有一个适当的文件路径的目录,你有写权限(本地应用程序目录,因为在这种情况下,应该没问题虽然)。


  • 正如前面提到的,你重新设置相同的单元格值的4倍


  • 您正在创建相同的单元格样式多次(这不是缓存幕后,有很大程度上是可以被创造,所以如果你正在生成一对夫妇十万,你可能会进入行单元格样式数量有限麻烦


  • 您不要刷新()的close()写你的工作簿后流。流在Java中哪些需要precious资源被手动关闭。


  • 没有堆栈跟踪这很难说100%,你所看到的ArrayOutOfBound问题是从哪里来的,但是我的猜测是,你要访问一个项目(从项目集合)的索引不存在,这是你从排索引,而不是你的项目清单驾驶报表数据的结果。


此外,由于你是很新的Java的一对夫妇的指引,让你产生对未来有希望更好,更不容易出错code:


  • 使用正确的Java命名约定 - 请遵循标准的Java命名约定 HTTP ://java.about.com/od/javasyntax/a/nameconventions.htm ,你的code会更容易阅读和推理(特别是当你在寻找来自社会的帮助) - 即sentorder类应该被命名为SentOrder。


  • 请尽量把code分割成更小,更容易测试模块,即你可以有一个帮手,从你的主要方法名为 createDataRow 法中,通常有不止在一个方法夫妇内循环使得他们极其困难的测试,调试和推理。


  • 除非你真的需要生成.xls格式,可以考虑使用XSSF *类生成XLSX文件 - 它有许多改进,在HSSF *(包括更好的支持DATAFORMAT)


有那些记住我已经重写你的例子:

 公共无效改善(表< SentOrder>项目)抛出IOException
    HSSFWorkbook工作簿=新HSSFWorkbook();
    HSSFSheet片= workbook.createSheet(MyNewSheet);    HSSFCellStyle styleOfCell = workbook.createCellStyle();
    styleOfCell.setDataFormat(HSSFDataFormat.getBuiltinFormat(M / D / YY));
    styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
    styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);    INT的rowIndex = 0;
    对于(SentOrder项目:项目){
        HSSFRow行= sheet.createRow(rowIndex位置++);
        HSSFCell nameCell = row.createCell(0);
        nameCell.setCellValue(item.getPartName());
        HSSFCell numberCell = row.createCell(1);
        numberCell.setCellValue(item.getPartNumber());
        HSSFCell quantityCell = row.createCell(2);
        quantityCell.setCellValue(item.getQuantity());
        HSSFCell dateCell = row.createCell(3);
        dateCell.setCellValue(新的Date());
        dateCell.setCellStyle(styleOfCell);
    }    FileOutputStream中OS =新的FileOutputStream(order_receipt.xls);
    尝试{
        workbook.write(OS);
    } {最后
        os.flush();
        os.close();
    }
}

I am absolute new to the Eclipse Java coding. I am trying to finish a project for managing the inventory. The part i am having trouble with is that, when I tried to write the items into the excel cell, I got errors saying that the array is out of bounds.

PS: item and item.getPartname etc are all defined under another class file. Please help. thanks

            FileOutputStream os =new FileOutputStream("orderreceipt");
            //Create a new workbook for writing data
            HSSFWorkbook wb2 = new HSSFWorkbook();
            //Create a new sheet:
            HSSFSheet newsheet = wb2.createSheet("MyNewSheet");
            //Create a new row:

            for (int i=0; i<6; i++){
                HSSFRow newrow = newsheet.createRow(i);
                sentorder item = (sentorder)items.get(i);
                for (short j=0; j<5; j++){
                    HSSFCell cell = newrow.createCell(j);

                    cell.setCellValue(item.getPartname());
                    cell.setCellValue(item.getPartnumber());
                    cell.setCellValue(item.getQuantity());
                    cell.setCellValue(new Date());
                      HSSFCellStyle styleOfCell = wb2.createCellStyle();
                      styleOfCell.setDataFormat(HSSFDataFormat
                          .getBuiltinFormat("m/d/yy"));
                      styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
                      styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);
                      cell.setCellStyle(styleOfCell);

                    }}
            wb2.write(os);
    }

解决方案

I can see quite a few problems with the attached code:

  • Missing file extension when creating new FileOutputStream - since you're generating the .xls workbook, you'd probably like to store it in the XLS file (the extension is not added automatically), also just make sure you have a proper file path to the directory you have write permissions (local application dir, as in this case should be ok though).

  • As already mentioned you are re-setting the same cell value 4 times

  • You are creating the same cell style multiple times (this is not cached behind the scenes and there is largely limited number of cells styles which can be created so if you were generating a couple thousands of rows you might get into troubles

  • You don't flush() and close() stream after writing your workbook. Streams in Java a precious resources which need to be manually closed.

  • Without stack trace it's difficult to say 100% where the ArrayOutOfBound issue you're seeing is coming from, however my guess would be that you're trying to access a item (from items collection) with the index that doesn't exist, which is a consequence that you're driving your report data from row indexes instead of the list of items you have.

Also, since you're quite new to Java a couple of guidelines which will allow you to produce hopefully better and less error-prone code in the future:

  • Use proper Java naming convention - please follow standard Java naming convention http://java.about.com/od/javasyntax/a/nameconventions.htm , your code will be easier to read and reason about (especially when you're looking for help from community) - i.e. sentorder class should be named as SentOrder.

  • Try to split your code into smaller, more testable modules i.e. you can have a helper createDataRow method called from your main method, in general having more than a couple of inner loops in one method makes them incredibly difficult to test, debug and reason about.

  • Unless you really need to generate .xls format, consider using XSSF* classes for generating xlsx document - it has many improvements over HSSF* (including much better dataFormat support).

Having those in mind I've rewritten your example:

public void improved(List<SentOrder> items) throws IOException {
    HSSFWorkbook workbook = new HSSFWorkbook();
    HSSFSheet sheet = workbook.createSheet("MyNewSheet");

    HSSFCellStyle styleOfCell = workbook.createCellStyle();
    styleOfCell.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
    styleOfCell.setFillForegroundColor(HSSFColor.AQUA.index);
    styleOfCell.setFillPattern(HSSFCellStyle.BORDER_THIN);

    int rowIndex = 0;
    for(SentOrder item : items) {
        HSSFRow row = sheet.createRow(rowIndex++);
        HSSFCell nameCell = row.createCell(0);
        nameCell.setCellValue(item.getPartName());
        HSSFCell numberCell = row.createCell(1);
        numberCell.setCellValue(item.getPartNumber());
        HSSFCell quantityCell = row.createCell(2);
        quantityCell.setCellValue(item.getQuantity());
        HSSFCell dateCell = row.createCell(3);
        dateCell.setCellValue(new Date());
        dateCell.setCellStyle(styleOfCell);
    }

    FileOutputStream os = new FileOutputStream("order_receipt.xls");
    try {            
        workbook.write(os);
    } finally {
        os.flush();
        os.close();
    }
}

这篇关于写项目到Excel单元格中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆