Inserting data from Excel into the database
Learn how to Insert data from Excel into the database using excel connector.
Step 1: Import excel-connector to project
- Download the latest excel-connector zip here
- Import the downloaded excel-connector zip into your app using the Import Resource option to the Connector folder.
Step 2: Import a databaseService
- In this example using excel connector we will be inserting data to HRDB User table
- Import Sample HRDB
Step 3: Creating Java Service
Create a Java Service, named ExcelService
Add the following import statements in the Java service created in the above step.
import java.util.List;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
import com.wavemaker.connector.excel.ExcelConnector;
import com.exceldemo.hrdb.User;
import com.exceldemo.hrdb.service.UserService;Follow below code snippet for creating a method to insert data to HRDB database User table from excel file
@ExposeToClient
public class ExcelService {
private static final Logger logger = LoggerFactory.getLogger(ExcelService.class);
@Autowired
private UserService userService;
@Autowired
private ExcelConnector excelConnector;
public void createUsersFromExcelFile(MultipartFile file) throws IOException {
List<User> usersList = excelConnector.readExcelAsObject(file.getInputStream(), User.class);
usersList.forEach(user -> {
userService.create(user);
});
}
}
Step 4: Integrating with UI
- Drag and Drop a FileUpload widget
- Create a Database CRUD variable for HRDB User table with name as
HrdbUserData
- Drag and Drop a Data Table from the existing Database CRUD variable
HrdbUserData
- Create a JavaService variable for the ExcelService created in the previous step with name as
userCreationVariable
and bind variable parameter toWidgets.fileupload1.selectedFiles[0]
and on the onSuccess event of variable giveHrdbUserData
variable - For fileUpload widget onSelect event Callback give variable
userCreationVariable
Done, now our aplication will take excel file as input and inserts that data into user table of the database
Java Service Use Cases