Прочитайте пути к папкам из excel и создайте папки в documentum с помощью java

Я хочу прочитать и получить пути к папкам из листа Excel в столбце "FolderPath" и создать список структур папок в родительской папке с именем "Documentum". Я прикрепил образец данных Excel, как показано ниже. Я могу создать папку из приведенного ниже кода, жестко закодировав путь к создаваемой папке. Например, в данном случае это: /documentum.

Путь к папке

/documentum/folder1

/documentum/folder2

/documentum/folder3

/documentum/folder8/folder9

**

Пожалуйста, предложите, как я могу добавить эту функцию в мой код ниже. Я пытался использовать excel POI, но мне не повезло, так как я мало работал с POI, поэтому могут помочь любые примеры модификаций или предложений по приведенному ниже коду.

package com.documentum;

import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.IDfId;
import com.documentum.fc.common.IDfLoginInfo;

import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;

import java.util.StringTokenizer;

import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;

public class AutoFolderStructure
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        String username = "user";
        String password = "docu";
        String repoName = "documentum";
        String folderPath = "/documentum"; //folder path to be created

        IDfSessionManager sessMgr = null;
        IDfSession sess = null;
        try
        {
            sessMgr = createSessionManager();
            addIdentity(sessMgr,username,password,repoName);
            sess = sessMgr.getSession(repoName);
            IDfId newId = createFolder(sess,folderPath,null,null,null);
            System.out.println("Created folder: " + newId);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            if((sessMgr != null) && (sess != null))
            {
                sessMgr.release(sess);
            }
        }

    }



    public static IDfId createFolder(
       IDfSession sess,
       String path,
       String pathSep,
       String type,
       String basePath)
       throws DfException
    {
       boolean cabinetStillToBeProcessed = true;

       if (pathSep == null || (pathSep.length() == 0))
       {
          pathSep = "/";
       }

       if ((type == null) || (type.length() == 0))
       {
          type = "dm_folder";
       }

       IDfId currentId = null;

       StringBuffer bufFldrPath = new StringBuffer(48);
       if ((basePath != null) && (basePath.length() > 1))
       {
          currentId = getIdByPath(sess, basePath);
          if (!currentId.isNull())
          {
             //base path actually exists.
             bufFldrPath.append(basePath);
             cabinetStillToBeProcessed = false; //cabinet already processed due to base path.

             int basePathLen = basePath.length();            
             if(basePathLen < path.length())
             {
                path = path.substring(basePath.length());
             }            
          }

       }

       StringTokenizer tokFldrNames = new StringTokenizer(path, pathSep);

       if (cabinetStillToBeProcessed)
       {
          //Execution will come here only if basePath was not specified or
          //if specified basePath was not valid.
          String cabinetName = tokFldrNames.nextToken();
          StringBuffer cabQual = new StringBuffer(32);
          cabQual.append("dm_cabinet where object_name='").append(
             cabinetName).append(
             "'");

          currentId = sess.getIdByQualification(cabQual.toString());
          if (currentId.isNull())
          {
             //need to create cabinet.
             IDfFolder cab = (IDfFolder) sess.newObject("dm_cabinet");
             cab.setObjectName(cabinetName);
             cab.save();
             currentId = cab.getObjectId();            
          }
          bufFldrPath.append(pathSep).append(cabinetName);
       }
       //By this point the bufFldrPath will either have the cabinet path
       //or it will have the basePath in it. 

       //now create all folders beyond the cabinet or basePath.
       while(tokFldrNames.hasMoreTokens())
       {         
          String parentPath = bufFldrPath.toString();

          String fldrName = tokFldrNames.nextToken();
          bufFldrPath.append(pathSep).append(fldrName);
          //by this point the buffer should contain the new expected path

          currentId = getIdByPath(sess,bufFldrPath.toString());
          if(currentId.isNull())
          {
             //looks like the new folder in the path does not exist.
             IDfFolder newFldr = (IDfFolder) sess.newObject(type);
             newFldr.setObjectName(fldrName);
             newFldr.link(parentPath);
             newFldr.save();
             currentId = newFldr.getObjectId();            
          }
          //by this point currentId should point to next folder in path                           
       }//while(all folder names)

       return currentId;
    }


    public static IDfId getIdByPath(IDfSession sess, String path)
       throws DfException
    {       

       int pathSepIndex = path.lastIndexOf('/');
       if (pathSepIndex == -1)
       {
          return new DfId("000");
       }

       StringBuffer bufQual = new StringBuffer(32);
       if (pathSepIndex == 0)
       {
          //its a cabinet path 
          bufQual.append(" dm_cabinet where object_name='");
          bufQual.append(path.substring(1));
          bufQual.append("'");
       }
       else
       {
          bufQual.append(" dm_sysobject where FOLDER('");
          bufQual.append(path.substring(0, pathSepIndex));
          bufQual.append("') ");
          bufQual.append(" and object_name='");
          bufQual.append(path.substring(pathSepIndex + 1));
          bufQual.append("'");
       }

       String strQual = bufQual.toString();
       IDfId id = sess.getIdByQualification(strQual);
       return id;
    }

    private static IDfSessionManager createSessionManager() throws DfException
    {
        IDfClientX clientX = new DfClientX();
        IDfClient localClient = clientX.getLocalClient();
        IDfSessionManager sessMgr = localClient.newSessionManager();
        return sessMgr;
    }


    private static void addIdentity(IDfSessionManager sm, String username,
            String password, String repoName) throws DfException
    {
        IDfClientX clientX = new DfClientX();

        IDfLoginInfo li = clientX.getLoginInfo();
        li.setUser(username);
        li.setPassword(password);

        // check if session manager already has an identity.
        // if yes, remove it.
        if (sm.hasIdentity(repoName))
        {
            sm.clearIdentity(repoName);
        }

        sm.setIdentity(repoName, li);
    }

}

Спасибо и с уважением Деб


person Dojo_user    schedule 05.05.2014    source источник
comment
Похоже, вы спрашиваете, как извлечь данные из Excel, но вы уже знаете, как сделать часть Documentum (создание папок из пути). Это правильно? В этом случае может быть лучше пометить это как вопрос Excel или Java, а не Documentum.   -  person Brendan Hannemann    schedule 13.05.2014
comment
да, вы правы, я хочу знать, как читать путь из excel, перебирать столбцы в листе excel для пути к папке и создавать папку в documentum. В настоящее время я могу создать папку /documentum, которая жестко запрограммирована в коде. Будут полезны любые предложения в Excel для чтения и записи для создания папки в documentum.   -  person Dojo_user    schedule 13.05.2014


Ответы (2)


Вы можете использовать библиотеку Apache POI. Вам нужно добавить его в свой путь к классам, если вы используете свой собственный скрипт, и в каталог java_methods, если вы выполняете задание documentum (выполняется documentum JMS)

person jeremyprioux    schedule 14.05.2014

Выложу сюда свой код работы с POI:

прежде всего:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

Вы можете извлечь из моего примера, как я работал с этим:

Я использовал:

Имя столбца 1 | Имя столбца 2 | Имя столбца 3 | Имя столбца 4

Данные здесь

Код: rowStart = 1; Означает, что я начинаю обработку со строки данных построчно. последняя колонка = 4; Означает, что у меня есть 4 столбца.

исправить код, как вы найдете likly.

// Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook;
        try
        {
            workbook = new XSSFWorkbook(file);

            // Get first/desired sheet from the workbook
            XSSFSheet sheet = workbook.getSheetAt(0);

            int rowStart = 1;
            int rowEnd = sheet.getLastRowNum();

            for (int rowNum = rowStart; rowNum < rowEnd; rowNum++)
            {
                Row r = sheet.getRow(rowNum);

                int lastColumn = 4;
                int inputtype = 0;
                table_no = "";
                dql = "";
                description = "";
                table_code = "";
                code = "";

                for (int cn = 0; cn < lastColumn; cn++)
                {
                    Cell cell = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);

                    if (cell == null)
                    {
                        switch (inputtype)
                        {
                        case 0:
                            inputtype++;
                            code = "";
                            break;
                        case 1:
                            inputtype++;
                            table_no = "";
                            break;

                        case 2:
                            inputtype++;
                            table_code = "";
                            break;
                        case 3:
                            inputtype++;
                            description = "";
                            break;

                        default:
                            inputtype = 0;
                            break;
                        }
                    }
                    else
                    {
                        switch (inputtype)
                        {
                        case 0:
                            inputtype++;
                            if (cell.getCellType() == Cell.CELL_TYPE_STRING)
                            {
                                code = cell.getStringCellValue();
                            }
                            else
                            {
                                tmp = cell.getNumericCellValue();
                                code = tmp.intValue() + "";
                            }
                            break;

                        case 1:
                            inputtype++;
                            if (cell.getCellType() == Cell.CELL_TYPE_STRING)
                            {
                                table_no = cell.getStringCellValue();
                            }
                            else
                            {
                                tmp = cell.getNumericCellValue();
                                table_no = tmp.intValue() + "";
                            }
                            break;

                        case 2:
                            inputtype++;
                            if (cell.getCellType() == Cell.CELL_TYPE_STRING)
                            {
                                table_code = cell.getStringCellValue().trim();
                            }
                            else
                            {
                                tmp = cell.getNumericCellValue();

                                table_code = tmp.intValue() + "";
                            }
                            break;
                        case 3:
                            inputtype++;
                            if (cell.getCellType() == Cell.CELL_TYPE_STRING)
                            {
                                description = cell.getStringCellValue();
                            }
                            else
                            {
                                tmp = cell.getNumericCellValue();

                                description = tmp.intValue() + "";
                            }
                            break;
                        default:
                            inputtype = 0;
                            break;
                        }
                    }
                }
person Tal.Bary    schedule 07.10.2014