Hey guys,
Please tell me how to load data from an excel file to a mysql database using jsp.

Dani AI

Generated

Following up on posts from , , and : import is two steps—read the workbook and write to the DB. Read the uploaded file directly in a servlet (no disk save needed) and pass the InputStream to Apache POI. Use JDBC prepared statements with batch updates and a transaction for reliability. The snippet below is a minimal, practical example that shows how to create a POI Workbook from the uploaded InputStream and insert rows into MySQL.

@MultipartConfig
public class ExcelUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Part filePart = req.getPart("file"); // form field name
        try (InputStream is = filePart.getInputStream();
             Workbook wb = WorkbookFactory.create(is);
             Connection conn = DriverManager.getConnection(dbUrl, dbUser, dbPass)) {

            conn.setAutoCommit(false);
            String sql = "INSERT INTO marks (student_id,name,mark) VALUES (?,?,?)";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                boolean header = true;
                Sheet sheet = wb.getSheetAt(0);
                for (Row row : sheet) {
                    if (header) { header = false; continue; } // skip header row
                    int id = (int) row.getCell(0).getNumericCellValue();
                    String name = row.getCell(1).getStringCellValue();
                    double mark = row.getCell(2).getNumericCellValue();
                    ps.setInt(1, id);
                    ps.setString(2, name);
                    ps.setDouble(3, mark);
                    ps.addBatch();
                }
                ps.executeBatch();
            }
            conn.commit();
        } catch (Exception e) {
            // rollback and proper error handling here
        }
    }
}

Notes and troubleshooting tips: use WorkbookFactory.create(InputStream) so both .xls and .xlsx work; for Servlet 2.x use Apache Commons FileUpload instead of @MultipartConfig; validate and coerce cell types (cells can be blank, strings, numbers, dates); wrap DB work in a transaction and roll back on error; for very large files avoid loading the whole workbook—use POI’s streaming/event APIs (XSSF event model or a streaming reader) to prevent OOM; if you can produce a CSV and have DB access, LOAD DATA INFILE will be much faster. As noted, keep upload/processing in a servlet/back-end component rather than embedding logic in a JSP.

Recommended Answers

All 9 Replies

You need to find a way to read the excel file. Once you do that, then it is easy. Call methods that save values to the database and pass as arguments the values read from the excel.

You will need 2 different things. Write methods that write to the database.
Find a way to read the contents of an excel file.

What exactly is your problem?

i have this excel sheet names "marks.xls". The xls file consists of marks of students. I want to add these marks to the mysql database.
I read somewhere that it is better to convert the xls file to cvs format and then insert it into the database from the cvs but i m not getting any success. Please suggest.

Where are you having problems:
- Convert excel to csv
- Read values
- Save to DB

Those are different unrelated issues. You can do one without having done the other.

Another option would be to read excel with Apache POI and save values in db

that would be best. Even better would be to not use a JSP at all for it.

that would be best. Even better would be to not use a JSP at all for it.

Well if you need to upload file where only registered users are allow to do so you will need JSP or JSF...

Well if you need to upload file where only registered users are allow to do so you will need JSP or JSF...

Nope. Use an html page to allow entering credentials and upload information for the file, which is submitted to a servlet.
You could conceivably use a JSP to display the results of the operation (maybe a tabular view of the data inserted) but that's not part of the "upload data" requirement.

Hey Peter..
I downloaded the POI package and directly uploaded the file to the db...Thnx...

After uploading a excel file from jsp then send to servlet now how to get details from excel file in servlet .........from any drve likec://my.xls is working fine but i dont want to save just get the data and update db thats it...but i am not able to do that plz show the code ho to make a xl file in servlet from input stream ...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.