user1707942
user1707942

Reputation: 15

Upload and read the excel file and insert the data in Database using groovy grails

Here is the GSP code:

<!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>

Here is the Controller:

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')
    }

I am getting the spring based exception

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

Upvotes: 0

Views: 3449

Answers (2)

tim_yates
tim_yates

Reputation: 171084

You cannot pass a CommonsMultipartFile to the constructor of XSSFWorkbook

Instead, pass an InputStream:

    XSSFWorkbook book = new XSSFWorkbook( file.inputStream )

Upvotes: 1

Joshua Moore
Joshua Moore

Reputation: 24776

The constructor for XSSFWorkbook requires an InputStream. So the constructor should look like this:

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

You can look at the related API docs for both XSSFWorkbook and CommonsMultipartFile for more information.

Upvotes: 3

Related Questions