上传并读取excel文件,并使用groovy grails在数据库中插入数据

这是GSP代码:

<!DOCTYPE html> <html> <head> <meta name="layout" content="main"> <title>Upload New Document</title> </head> <body> <div class="nav" role="navigation"> <ul><li><g:link class="list" action="list">Document List</g:link></li></ul> </div> <div class="content scaffold-create" role="main"> <h1>Upload New Document</h1> <g:if test="${flash.message}"><div class="message" role="status">${flash.message}</div></g:if> <g:uploadForm action="upload"> <fieldset class="form"> <input type="file" name="file" /> </fieldset> <fieldset class="buttons"> <g:submitButton name="upload" class="save" value="Upload" /> </fieldset> </g:uploadForm> </div> </body> </html> 

这是控制器:

 def upload() { def file = request.getFile('file') // inp = new FileInputStream(uploadedFile); XSSFWorkbook book = new XSSFWorkbook(file); XSSFSheet[] sheets = book.sheets; for (XSSFSheet sheet : sheets) { println("\nSHEET NAME:"+sheet.getSheetName()+"\n"); sheet.each { row -> Iterator cellIterator = row.cellIterator(); while(cellIterator.hasNext()) { XSSFCell cell = cellIterator.next(); print(getCellValue(cell)+" "); } println(); } } if(file.empty) { flash.message = "File cannot be empty" } else { def documentInstance = new Document() documentInstance.filename = file.originalFilename documentInstance.filedata = file.getBytes() documentInstance.save() } redirect (action:'list') } 

我得到了基于spring的例外

 Could not find matching constructor for: org.apache.poi.xssf.usermodel.XSSFWorkbook(org.springframework.web.multipart.commons.CommonsMultipartFile) 

XSSFWorkbook的构造XSSFWorkbook需要一个InputStream 。 所以构造函数应该是这样的:

 XSSFWorkbook book = new XSSFWorkbook(file.getInputStream()); 

您可以查看XSSFWorkbook和CommonsMultipartFile的相关API文档以获取更多信息。

您不能将CommonsMultipartFile传递给CommonsMultipartFile的构造XSSFWorkbook

相反,传递一个InputStream

  XSSFWorkbook book = new XSSFWorkbook( file.inputStream )