Importing Multiple Users via Excel in Liferay: A Step-by-Step Guide

Introduction 

This code extends the capabilities of Liferay, a powerful platform for web applications, by enhancing its functionality to seamlessly integrate with Excel files. Specifically, it facilitates the streamlined process of creating users directly from Excel files, eliminating the need for manual data entry and providing a more efficient and automated approach to user management within the Liferay environment.

Understanding the code

1 - Excel File Handling:

The “getWorkbook” method is responsible for creating a workbook instance based on the type of Excel file (XLS or XLSX) provided as input.

private static Workbook getWorkbook(FileInputStream inputStream, String excelFilePath) throws IOException {
    Workbook workbook = null;
    if (excelFilePath.endsWith("xlsx")) {
        workbook = new XSSFWorkbook(inputStream);
    } else if (excelFilePath.endsWith("xls")) {
        workbook = new HSSFWorkbook(inputStream);
    } else {
        throw new IllegalArgumentException("The specified file is not an Excel file");
    }
    return workbook;
}

2 - Excel Reading:

The “readingExcel” method reads data from the uploaded Excel file. It iterates through rows and calls the “addUser” method for each row after skipping the header.

private boolean readingExcel(File file, ActionRequest actionRequest) throws IOException {
    boolean isUploadSuccessful = false;
    try (FileInputStream inputStream = new FileInputStream(file);) {
        Workbook wb = getWorkbook(inputStream, file.getPath());
        int c = 0;
        if (Validator.isNotNull(wb)) {
            Sheet firstSheet = wb.getSheetAt(0);
            Iterator<Row> iterator = firstSheet.iterator();
            while (iterator.hasNext()) {
                System.out.println("c is" + c);
                Row row = iterator.next();
                if (row.getRowNum() == 0) {
                    continue;
                }
                addUser(row, actionRequest);
                c++;
            }
        }
    }
    return isUploadSuccessful;
}

3 - User Creation:

The “addUser” method processes each cell in a row, extracting user information such as ScreenName, FullName, Organization, Roles, and Email. It then uses Liferay's UserLocalServiceUtil to add a new user using Liferay's services.

public void addUser(Row row, ActionRequest actionRequest) { // User creation logic from Excel data
    Iterator<Cell> cellIterator = row.cellIterator();
    String ScreenName = null;
    String FullName = null;
    String Organization = null;
    String Roles = null;
    String Email = null;
    System.out.println("outside while first if");
    while (cellIterator.hasNext()) {
        Cell cell = cellIterator.next();
        cell.setCellType(Cell.CELL_TYPE_STRING);
        System.out.println("outside first if");
        if (0 == cell.getColumnIndex()) {
            System.out.println("inside first if");
            ScreenName = cell.getStringCellValue();
        } else if (1 == cell.getColumnIndex()) {
            FullName = cell.getStringCellValue();
        } else if (2 == cell.getColumnIndex()) {
            Organization = cell.getStringCellValue();
        } else if (3 == cell.getColumnIndex()) {
            Roles = cell.getStringCellValue();
        } else if (4 == cell.getColumnIndex()) {
            Email = cell.getStringCellValue();
            try {
                ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
                ServiceContext serviceContext = new ServiceContext();
                serviceContext.setScopeGroupId(20121L);
                long companyId = PortalUtil.getDefaultCompanyId();
                System.out.println("companyId ==> "+companyId);
                long groupId = serviceContext.getScopeGroupId();
                System.out.println("groupId ==> "+groupId);
                System.out.println("serviceContext ==> "+serviceContext);
                Locale locale = Locale.US;
                System.out.println("locale ==> "+locale);
                long contactId = 20121;
                Date today = new Date();
                UserLocalServiceUtil.addUser(20123, companyId, true,
                    UserImportPortletKeys.USERIMPORT , UserImportPortletKeys.USERIMPORT, false, ScreenName,Email, locale, ScreenName, "", UserImportPortletKeys.USERIMPORT, Integer.parseInt("01"), Integer.parseInt("01"), false, 0, 1, 1970 , "", Integer.parseInt("01"), null, null, null , null, false, new ServiceContext());
                System.out.println("============== ======= ==> ");
            } catch (Exception e1) {
                System.out.println("================error in creating user==============="+e1);
            }
        }
    }
}

4 - File Upload Handling:

The “uploadURL” method, annotated with “@ProcessAction”, handles the file upload using Liferay's UploadPortletRequest and triggers the Excel reading process.

@ProcessAction(name="uploadURLs")
public void uploadURL(ActionRequest actionRequest, ActionResponse actionResponse)
        throws PortletException, IOException {
    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
    File file = uploadRequest.getFile("userFile");
    readingExcel(file, actionRequest);
}

5 - Portlet Configuration:

The portlet is configured with properties such as display category, header portlet CSS, display name, template path, view template, etc.

@Component(
    property = {
        "com.liferay.portlet.display-category=category.sample",
        "com.liferay.portlet.header-portlet-css=/css/main.css"
    }
)

6- Error Handling :

The code error includes error handling, printing messages to the console in case of exceptions during user creation.

Conclusion

The UserImportPortlet code is a Liferay MVCPortlet designed for streamlined user imports from Excel files. It handles file uploads, reads Excel data, and uses Liferay's UserLocalServiceUtil to create users based on the imported information

Blogs

I'm a bit confused. Is this just partial sample code or can the actual complete MVCPortlet code be downloaded somewhere?