excel - 在grails中实现excel导入的高效方法

标签 excel grails groovy apache-poi

这段代码可能应该进入代码审查,但我不会在那里得到快速回复(那里只有 2 个绝妙的问题)。 我有以下代码用于将数据从 excel 导入到我的 grails 应用程序中。问题是我没有测试 Excel 文件中超过 1000 行的数据,因此当我的客户尝试上传 13k 行时,我的应用程序卡住了。我已经检查了 stacktrace.log (应用程序正在生产中)但没有异常(exception)。系统管理员认为 jvm 内存不足。我们增加了堆内存的大小。 但是,我想问是否有更好的方法来实现这一点。我正在使用 apache poi 并在从 excel 读取每一行时创建域对象。之后,我将对象列表传递给 Controller ​​,该 Controller 验证它们并将其保存在数据库中。 我应该告诉我的客户限制一次导入的项目数量吗? 是否有更好的方法来编写此代码?

def importData(file, user){
    def rows = []
    def keywords = Keyword.list()
    int inventoryCount = Inventory.findAllByUser(user).size()

    def inventory = new Inventory(name:"Inventory ${inventoryCount +1}", user:user)

    Workbook workbook = WorkbookFactory.create(file)
    Sheet sheet = workbook.getSheetAt(0)

    int rowStart = 1;
    int rowEnd = sheet.getLastRowNum() + 1 ;
    for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
        Row r = sheet.getRow(rowNum);

        if(r != null && r?.getCell(0, Row.RETURN_BLANK_AS_NULL)!=null ){
            def rowData =[:]
            int lastColumn = 8;
            for (int cn = 0; cn < lastColumn; cn++) {
                Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
                if (c == null) {
                    return new ExcelFormatException("Empty cell not allowed",rowNum+1, cn+1)
                } else {

                    def field = properties[cn+1]
                    if(field.type==c.getCellType()){
                        if(c.getCellType()==text){

                            rowData<<[(field.name):c.getStringCellValue().toString()]
                        }else if(c.getCellType()==numeric){
                            if(field.name.equalsIgnoreCase("price") ){
                                rowData<<[(field.name):c.getNumericCellValue().toDouble()]
                            }else{
                                rowData<<[(field.name):c.getNumericCellValue().toInteger()]
                            }
                        }
                    }else{
                        return new ExcelFormatException("Invalid value found", rowNum+1, cn+1)
                    }
                }

            }

            def item = new InventoryItem(rowData)
            String keyword = retrieveKeyword(item.description, keywords)
            String criticality = keyword?"Critical":"Not known"
            int proposedMin = getProposedMin(item.usagePerYear)
            int proposedMax = getProposedMax(proposedMin, item.price, item.usagePerYear, item?.currentMin)
            String inventoryLevel = getInventoryLevel(item.usagePerYear, item.quantity, proposedMin, item.currentMin) 

            item.proposedMin = proposedMin
            item.proposedMax = proposedMax
            item.inventoryLevel = inventoryLevel
            item.keyword = keyword 
            item.criticality = criticality

            inventory.addToItems(item)
        }

    }

    return inventory
}

上面代码中使用的函数:

def retrieveKeyword(desc, keywords){
    def keyword
    for (key in keywords){
        if(desc.toLowerCase().contains(key.name.toLowerCase())){
            keyword = key.name
            break
        }
    }
    return keyword
}
int getProposedMin(int usage){
    (int) ((((usage/12)/30) *7) + 1)
}


int getProposedMax(int pmin, double price, int usage, int cmin){
    int c = price == 0? 1: ((Math.sqrt((24 * (usage/12)*5)/(0.15*price))) + (pmin - 1))
    if(cmin >= c){
        return pmin
    }
    return c
}

String getInventoryLevel(int usage, int qty, int proposedMin, int currentMin){
    if(qty != 0){
        double c = usage/qty
        if(usage==0)
            return "Excess"
        if(c<0.75){
            return "Inactive"
        }else if(proposedMin<currentMin){
            return "Excess"
        }else if(c>=0.75){
            return "Active"
        }
    }else if(usage==0 && qty == 0){
        return "Not used"
    }else if(usage>3 && qty ==0){
        return "Insufficient"
    }else if(proposedMin > currentMin){
        return "Insufficient"
    }

}

Controller 操作:

def importData(){
    if(request.post){
        def file = request.getFile("excelFile")

        //validate file
        def file_types = ["application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]

        if(!file_types.contains(file.getContentType())){
            render view:"importData", model:[error:"Invalid File type"]
            return
        }

        def inv = excelService.importData(file.getInputStream(),User.get(principal.id))
        if(inv){
            if(inv instanceof ExcelFormatException){
                def err = (ExcelFormatException) inv
                render view:"importData", model:[error:err.message +". Error occurred at: Row: "+err.row+" Col: "+err.col]
                return
            }else{
                render view:"viewData", model:[inventory:inv]
                return
            }
        }
    }


}

最佳答案

在处理批量导入时,Hibernate 和 GORM 需要进行一些调整。两个建议:

  1. 遵循此处的技术:http://naleid.com/blog/2009/10/01/batch-import-performance-with-grails-and-mysql (考虑到 MySQL 编写,但这些概念与任何 RDBMS 相关)

  2. 不要使用集合来映射 InventoryInventoryItem 之间的关系。从 Inventory 中删除 items 集合,并将 Inventory 字段添加到 InventoryItem 类中。 Burt Beckwith 在此详细介绍了这一点:http://burtbeckwith.com/blog/?p=1029

关于excel - 在grails中实现excel导入的高效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21175408/

相关文章:

grails - Grails GSP-无法使用参数调用主体

mysql - Grails 2.4.3 & MySQL & grails.project.fork = false

java - 在 groovy 中获取 "java.sql.SQLException: ORA-28009: connection as SYS should be as SYSDBA or SYSOPER"

vba - 如何将=MATCH()公式翻译成VBA

html - 如何将 Excel 格式的文本转换为 HTML?

excel - 无法在 VbScript 中复制 Excel 中的大量数据

intellij-idea - @Grab 不能在用于 groovy 的 intellij IDE 中工作

c# - 解析现有的 "complex"SQL 语句并转换为对自定义 API 调用的调用

grails - Grails-更少的CSS @import问题

java - 在java和groovy中准确表示时间