Advertisement
ramkesheoran

Import data from excel file

Aug 1st, 2012
3,106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
XPP 9.30 KB | None | 0 0
  1. Create a class firstly :
  2. // gl00mie, import data from Excel via ADO, 20061220 -->
  3. // How to use this class:
  4. // 1. Create class instance, specify filename and (optional) cursor type e.g.
  5. //    doc = new ExcelImportADO(strFilename, #adOpenStatic);
  6. // 2. Read names of worksheets present in the file, suppress error messages if necessary
  7. //    con = doc.getExcelSheetNames();
  8. // 3. Specify the name of the worksheet to open ADODB.Recordset on, otherwise the first one will be used
  9. //    doc.excelSheetName(conpeek(con,2));
  10. // 4. Open the file, i.e. open ADODB.Recordset (and ADODB.Connection if it's not opened yet)
  11. //    suppress error messages if necessary and check for result:
  12. //    if(doc.openFile(false)) ...
  13. // 5. Check if there is a correct number of columns in the Recordset
  14. //    if(doc.getFieldsCount() > 7) ...
  15. // 6. Get the total record count if #adOpenStatic cursor type is used
  16. //    cnRecords = doc.getRecordCount();
  17. // 7. Read records in a loop, use indexes (1..n) or field names to identify fields
  18. //    By default field values are returned as strings
  19. //    int   i;
  20. //    real  r;
  21. //    str   s;
  22. //    while(!doc.eof())
  23. //    {
  24. //        i = doc.getFieldValue(1, false);
  25. //        s = doc.getFieldValue('stringField');
  26. //        r = doc.getFieldValue('numericField', false);
  27. //        doc.moveNext();
  28. //    }
  29. // 8. Cleanup - close ADODB.Recordset and ADODB.Connection
  30. //    doc.finalize();
  31. class ExcelImportADO
  32. {
  33.     COM         cnnExcel, rstExcel, flds;                       // ADO: Connection, Recordset, Fields
  34.     str         strFileName, strSheetName;
  35.     int         nCursorType;                                    // ADO: CursorTypeEnum
  36.     container   conSheetNames;                                  // Excel Worksheets names
  37.  
  38.     // %1 - full file name
  39.     #localmacro.ADODBExcelConnString
  40.         "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + %1 + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"
  41.     #endmacro
  42.     #CCADO
  43. }
  44. // gl00mie, import data from Excel via ADO, 20061220 <--
  45.  
  46.  
  47. // take a variant value recieved via ADO and transform it from
  48. // Excel-related types subset into a suitable type for Axapta
  49. protected anytype adoValue(COMVariant _val, int _type)
  50. {
  51.     switch (_type)
  52.     {
  53.         // constants for types recognized by ADO for Excel
  54.         case #adDouble:         return _val.double();
  55.         case #adCurrency:       return _val.currency();
  56.         case #adDate:           return _val.date();
  57.         case #adBoolean:        return _val.boolean();
  58.         case #adVarWChar,
  59.              #adLongVarWChar:   return _val.bStr();
  60.     }
  61.     return '';
  62. }
  63.  
  64.  
  65. // take a variant value recieved via ADO and transform it from
  66. // Excel-related types subset into a STRING value suitable for Axapta info-windows
  67. protected str adoValueStr(COMVariant _val, int _type, boolean bDblRound = false)
  68. {
  69.   //  if(_type == 5)
  70.   //  _type = 202;
  71.  
  72.     switch (_type)
  73.     {
  74.         case #adDouble:         return num2str(_val.double(),-1,(bDblRound ? 0 : -1),1,0);
  75.         case #adCurrency:       return num2str(_val.currency(),-1,-1,1,0);
  76.         case #adDate:           return date2str(_val.date(),123,2,2,2,2,4);
  77.         case #adBoolean:        return int2str(_val.boolean());
  78.         case #adVarWChar,
  79.              #adLongVarWChar:   return _val.bStr();
  80.     }
  81.     return '';
  82. }
  83.  
  84.  
  85. // return Recordset.EOF()
  86. boolean eof()
  87. {
  88.     return (rstExcel ? rstExcel.EOF() : true);
  89. }
  90.  
  91.  
  92. // get Excel book first sheet's name or previously
  93. // set sheet name to use as a table name in select
  94. str excelSheetName(str _name = '')
  95. {
  96.     if(!prmisdefault(_name))
  97.         strSheetName = _name;
  98.     else
  99.     if(!strSheetName)                   // have we been already called successfully?
  100.         strSheetName = conpeek(this.getExcelSheetNames(), 1);
  101.     return strSheetName;
  102. }
  103.  
  104.  
  105. // close ADO RecordSet and Connection
  106. public void finalize()
  107. {
  108.     // RecordSet is closed automatically upon Connection closure
  109.     if (cnnExcel && cnnExcel.State() != #adStateClosed)
  110.         cnnExcel.Close();
  111. }
  112.  
  113.  
  114. // return ADO Connection object
  115. // create and open the connection if necessary
  116. public COM getConnection()
  117. {
  118.     if(!cnnExcel)
  119.     {
  120.         cnnExcel = new COM(@"ADODB.Connection");
  121.         cnnExcel.connectionString(#ADODBExcelConnString(strFileName));
  122.         cnnExcel.Open();
  123.     }
  124.     return cnnExcel;
  125. }
  126.  
  127.  
  128. // get Excel worksheet names
  129. container getExcelSheetNames(boolean _suppressErrors = false)
  130. {
  131.     COM sheets, sheet;
  132.     COM adoxCatalog = new COM(@"ADOX.Catalog");
  133.     int cnSheets, i;
  134.     int nLines;
  135.     str strSheet;
  136.     ;
  137.     if(conSheetNames)
  138.         return conSheetNames;
  139.     try
  140.     {
  141.         nLines   = infolog.line();                      // save current infolog level
  142.         adoxCatalog.ActiveConnection(this.getConnection());
  143.         sheets   = adoxCatalog.Tables();
  144.         cnSheets = sheets.count();
  145.         for(i=0; i < cnSheets; i++)
  146.         {
  147.             sheet    = sheets.item(i);
  148.             strSheet = sheet.name();
  149.             // strip '$' and anything beyond it (in case there are autofilters in the workbook)
  150.             // also strip "'" for quoted names
  151.             strSheet = strrem(substr(strSheet, 1, strscan(strSheet, '$', 1, strlen(strSheet))-1),'\'');
  152.             if(!confind(conSheetNames, strSheet))
  153.                 conSheetNames += strSheet;
  154.         }
  155.     }
  156.     catch (Exception::Error)
  157.     {
  158.         if (cnnExcel && cnnExcel.State() != #adStateClosed)
  159.             cnnExcel.Close();
  160.         cnnExcel = null;                                // release ADODB.Connection object
  161.         if (_suppressErrors)
  162.             infolog.clear(nLines);                      // delete infolog messages generated in try block
  163.         else
  164.             error("@SYS59927");
  165.     }
  166.     return conSheetNames;
  167. }
  168.  
  169.  
  170. // return Recordset.Fields.Count
  171. int getFieldsCount()
  172. {
  173.     return (flds ? flds.Count() : -1);
  174. }
  175.  
  176.  
  177. // read _fldId-th field from the current ADO RecordSet
  178. // and transform it into a type suitable for Axapta.
  179. // _fldId can be an int index starting 1 or a column name
  180. anytype getFieldValue(anytype _fldId, boolean _asString = true)
  181. {
  182.     COM fld;                                // ADO: Field
  183.     ;
  184.     setprefix(strfmt(@"%1::%2()", classId2Name(classIdGet(this)), funcname()));
  185.     if(!flds)
  186.         throw error(strfmt('%1 %2', "@SYS68420", @"Fields"));
  187.     if(typeof(_fldId) == Types::Integer)
  188.         _fldId--;                           // ADO uses indexes starting 0, not 1
  189.     fld = flds.Item(_fldId);
  190.     return (_asString ? this.adoValueStr(fld.Value(), fld.Type(), true) :
  191.                         this.adoValue   (fld.Value(), fld.Type()));
  192. }
  193.  
  194.  
  195. // return record count for the opened RecordSet
  196. // not valid for forward-only cursor or closed recordset
  197. // MAN
  198. // If the Recordset object supports approximate positioning or bookmarks - that is,
  199. // Supports(adApproxPosition) or Supports(adBookmark), respectively, return True
  200. // this value will be the exact number of records in the Recordset, regardless of
  201. // whether it has been fully populated. If the Recordset object does not support
  202. // approximate positioning, this property may be a significant drain on resources
  203. // because all records will have to be retrieved and counted to return an accurate
  204. // RecordCount value.
  205. // NOTE: In ADO versions 2.8 and earlier, the SQLOLEDB provider fetches all records
  206. // when a server-side cursor is used despite the fact that it returns True for both
  207. // Supports (adApproxPosition) and Supports (adBookmark).
  208. int getRecordCount()
  209. {
  210.     if(rstExcel && rstExcel.State() != #adStateClosed)
  211.         return rstExcel.RecordCount();
  212.     return -1;
  213. }
  214.  
  215.  
  216. // return ADO Recordset object
  217. public COM getRecordset()
  218. {
  219.     return rstExcel;
  220. }
  221.  
  222.  
  223. // call Recordset.MoveNext()
  224. void moveNext()
  225. {
  226.     if (rstExcel)
  227.         rstExcel.MoveNext();
  228. }
  229.  
  230.  
  231. public void new(str _fileName, int _cursorType = #adOpenForwardOnly)
  232. {
  233.     rstExcel    = null;
  234.     cnnExcel    = null;
  235.     strFileName = _fileName;
  236.     nCursorType = _cursorType;              // use #adOpenStatic to be able to read RecordCount
  237. }
  238.  
  239.  
  240. // try to open a sheet from an Excel file which name
  241. // has been passed to new() or got by excelSheetName()
  242. boolean openFile(boolean _suppressErrors = false)
  243. {
  244.     boolean ok = false;
  245.     int     nLines;
  246.     ;
  247.     nLines = infolog.line();                            // save current infolog level
  248.     try
  249.     {
  250.         if(this.excelSheetName() != '')
  251.         {
  252.             rstExcel    = new COM(@"ADODB.Recordset");
  253.             rstExcel.Open(@"SELECT * FROM [" + strSheetName + @"$]", this.getConnection(), nCursorType);
  254.             flds        = rstExcel.Fields();
  255.             ok = true;
  256.         }
  257.     }
  258.     catch  (Exception::Error)
  259.     {
  260.         if (cnnExcel && cnnExcel.State() != #adStateClosed)
  261.             cnnExcel.Close();
  262.         if (_suppressErrors)
  263.             infolog.clear(nLines);                      // delete infolog messages generated in try block
  264.     }
  265.     return ok;
  266. }
  267.  
  268.  
  269.  
  270. Job that will import data from excel file :
  271. static void Import_Data(Args _args)
  272. {
  273.     ExcelImportADO          excelimport;
  274.     ;
  275.     excelimport = new ExcelImportADO('D:\\ImportData\\Student.xls');
  276.     excelimport.openFile(false);
  277.     while (!excelimport.eof())
  278.       {
  279.        info(excelimport.getFieldValue(2));
  280.        excelimport.moveNext();
  281.      }
  282. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement