1

I have a web application from where I am uploading excel file and converting it into base64 and sending it to my rest api as a string, from my rest API i need to read that excel file and then I need to upload that file in my database (MYSQL), I don't want to save the file anywhere on disk, i want to read file in memory. I searched a lot on internet on how can i convert base64 to excel in java, but unfortunately i am not getting any solution.

Any help would be appreciated.

Rigsby
  • 180
  • 2
  • 14

2 Answers2

2

Apache POI is a good library to process excel files, here is a good tutorial to start with it, basically you have to convert your base base 64 file into an InputStream and from there use one of the WorkBook implementation that Apache POI provides to process the data.

David Florez
  • 1,460
  • 2
  • 13
  • 26
1

It makes no difference to Java if you have an image or an excel file. Below is a piece of exemplary code that I think should help you getting started. It is based on Write Base64-encoded image to file and the code provided there for decoding the base 64 encoded file and based on the instructions from https://www.codejava.net/java-se/jdbc/insert-file-data-into-mysql-database-using-jdbc. It should work for many databases as it is using only JDBC, but it is not tested against MySQL.

package net.codejava.jdbc;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

class JdbcInsertFileTwo {

    public static void main(String[] args) {

        String base64encoded = "asdf123";

        byte[] excelBytes = Base64.decodeBase64(base64encoded);

        String url = "jdbc:mysql://localhost:3306/contactdb";
        String user = "root";
        String password = "secret";

        try (Connection conn = DriverManager.getConnection(url, user, password)) {

            PreparedStatement statement = conn.prepareStatement("insert into table(name, data) " + "values(?,?)");
            statement.setString(1, "My file name.xls");
            statement.setBinaryStream(2, new ByteArrayInputStream(excelBytes), excelBytes.length);

            int row = statement.executeUpdate();
            if (row > 0) {
                System.out.println("The excel file was uploaded.");
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}