Jump to content
MrCheese

best way to extract data from excel based on common value in a column

Recommended Posts

Posted (edited)

Hi All,

Thanks so much in advance for your help!

I have a data set with 300,000 rows (in excel), with 14 columns. In the first column, I have a value, and there are only 10 unique values in this column across all whole data set.

I wish to extract these 10 separate data sets based on the common value in the first column.

I know there are multiple ways to do this, but in your experience, which is the best way?

I have come across/ thought of these ideas:

* focused in the excel udf using filter get, filter set, read to array, save to file 

* using this process, but I'm not sure if it does what I want: https://www.autoitscript.com/forum/topic/178998-solved-create-an-array-from-filtered-excel-sheet/

* read excel to array, copy row (column by column) to new array based on column value

*read excel to array, copy to temp array, delete row where its not the set value for this iteration, move to next iteration.

I've performed the last two when extracting full columns where there is a desired header to be extracted, whilst keeping a key_id field common across the extracts.

I don't need code written by anyone at this point, just a nudge in the right direction :D

 

Edited by MrCheese
changed topic header

Share this post


Link to post
Share on other sites

I would try to extract the whole sheet at once into a single 2D array, sort the array based on first column, then write the resulting array into 10 separate xls files.  I don't know if you need to repeat this process frequently, or if it is just a one time run.  I am saying this, because it might take quite some time to perform this way, but it would be very easy to code.

Share this post


Link to post
Share on other sites

Extracting the whole sheet (function _Excel_RangeRead) with 300.000 rows will not work as the UDF uses the Excel transpose function as a default which is limited to 16.384 rows (details can be found in the wiki).
Set parameter $bForceFunc to True so only AutoIt's array limit of about 16m cells applies.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (2018-12-03 - Version 1.4.11.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2019-03-02 - Version 1.3.5.0) - Download - General Help & Support - Example Scripts - Wiki
Outlook Tools (2019-01-22 - Version 0.1.0.0) - Download - General Help & Support
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Share this post


Link to post
Share on other sites
12 hours ago, water said:

Extracting the whole sheet (function _Excel_RangeRead) with 300.000 rows will not work as the UDF uses the Excel transpose function as a default which is limited to 16.384 rows (details can be found in the wiki).
Set parameter $bForceFunc to True so only AutoIt's array limit of about 16m cells applies.

Thanks Water. in light of the UDFs and excels limitations and intricacies, would you have a suggested a different way to do this? I can convert xlsx to csv, and use the csv phase / split functions.

Share this post


Link to post
Share on other sites
2 hours ago, MrCheese said:

I can convert xlsx to csv, and use the csv phase / split functions.

It's almost the same; only the way you get the 2-Dimension array changes.

You need to read the whole sheet in an array, then make a comparsion of a value to extract the data in separate files.

One of the easiest way yo do that is using _Excel_RangeRead() with the parameter $bForceFunc set to true as @water suggested, so you'll have the array with all the values, and then you can do whatever you want.

But, you could think to use an SQLite database either, which could save you for sure some time.

You can find Excel to SQLite converter(s) online, and manage all the SQLite stuffs using _SQLite_* functions in AutoIt :)


Click here to see my signature:

Spoiler

Thoughts:

  • I will always thank you for the time you spent for me.
    I'm here to ask, and from your response, I'd like to learn.
    By my knowledge, I can help someone else, and "that someone" could help in turn another, and so on.

/*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------*/

ALWAYS GOOD TO READ:

 

Share this post


Link to post
Share on other sites

A Excel workbook can be accessed like a database using ADO (example). This allows to bypass all Excel limitations.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (2018-12-03 - Version 1.4.11.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2019-03-02 - Version 1.3.5.0) - Download - General Help & Support - Example Scripts - Wiki
Outlook Tools (2019-01-22 - Version 0.1.0.0) - Download - General Help & Support
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Share this post


Link to post
Share on other sites

If the source Excel file is essentially permanent data, your best friend will be to extract an array (an SQL table in fact) from the sheet using Excel ADO interface and create an SQLite DB from that. You'll get all desirable flexibility with this setup.

If your source is expected to significantly vary over time (i.e. it isn't a one-time operation) you can just use Excel ADO to query it.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
23 hours ago, water said:

A Excel workbook can be accessed like a database using ADO (example). This allows to bypass all Excel limitations.

Once its accessed via ADO, and extract it into a SQLite DB (as jchd said), would you then use Autoit's sql commands on top, or would you just access it via a SQLite and use sql commands?

 

Share this post


Link to post
Share on other sites

Sorry but I don't understand what you mean by " use Autoit's sql commands on top ".

You just query the SQLite database with the SQLite.au3 UDF. Again if your source Excel file will change, the DB must be changed accordingly, so going thru SQLite isn't beneficial (details may muddy the border).

But if the Excel file is given once for all, you can most probably benefit from the power of SQLite queries, including add-on functions if necessary.
For instance, recent SQLite versions offer windowing features, full text table search (legacy feature), and a lot more.
It all depends on the needs you have and the complexity of your queries. The nice thing is that SQLite doesn't need any installation nor maintenance, contrary to "heavy" client-server DB engines.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

I am curious if this code could work on 300,000 rows.  I have Excell 2003, so I am limited to 65k rows.  But the result is quite fast.  Maybe you could try it :

#include <Excel.au3>
#include <MsgBoxConstants.au3>

Local $oExcel = _Excel_Open()
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error creating the Excel application object.")
Local $oWorkbook = _Excel_BookOpen($oExcel, "65000.xls")
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error opening Workbook")

_Excel_RangeSort($oWorkbook, Default, Default, "A:A")
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error sorting data.")

Local $iPrev = 1
Local $aResult = _Excel_RangeRead($oWorkbook, Default, "A:A")
For $i = 2 to 10
  $iFound = _ArraySearch ($aResult,$i,$iPrev-1,0,0,0,1,0)
  MakeCopy ($iPrev, $iFound, @ScriptDir & "\T" & $i-1 & ".xls")
  $iPrev = $iFound+1
Next
MakeCopy ($iPrev, UBound ($aResult), @ScriptDir & "\T10.xls")

Func MakeCopy ($iStart, $iEnd, $sName)

  Local $oRange = $oWorkbook.ActiveSheet.Range("A" & $iStart & ":N" & $iEnd)
  Local $oWB = _Excel_BookNew ($oExcel, 1)
  _Excel_RangeCopyPaste($oWB.ActiveSheet, $oRange, "A1")
  If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error copying cells." & "/" & @error)
  _Excel_BookSaveAs($oWB, $sName, $xlWorkbookNormal, True)
  If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error saving as" & "/" & @error)
  _Excel_BookClose ($oWB,False)

EndFunc

 

Share this post


Link to post
Share on other sites
Posted (edited)

Hi All, as an updated, I actually ended up needing to filter on two columns, which makes it more complex.

Keeping this in excel made it complex. and that next time I should look into using sql.

to compute 602,335 rows with ~21 possible filtered outcomes (3 in column X:X and 7 in column A:A) took 27mins to filter and extract and save each workbook.

I'm sure this can be optimised, but it works.

#include <Excel.au3>
#include <MsgBoxConstants.au3>
#include <Array.au3>

Local $oExcel = _Excel_Open() ;true,false,false)
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error creating the Excel application object.")
$dir = @ScriptDir & "\"
$book = "master_baseline.xlsx"
Local $oWorkbook = _Excel_BookOpen($oExcel, $dir & $book)
If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error opening Workbook")

$Fcol1 = "X"
$Fcol2 = "A"
$baserange = "A:X"

Global $aRowSort[0]
Global $aColUnique[0]

Global $aRowSort[] = [$Fcol1, $Fcol2]
$iRow = UBound($aRowSort)

$msg = "$iRow |" & $iRow
dbb()

;for each column that we want to sort on, lets extract all the unique rows into an array, and create a larger array containing those suparrays.
For $i = 0 To UBound($aRowSort) - 1
    $rowval = $aRowSort[$i]
    $rowsort = $rowval & ":" & $rowval
    $msg = "reading range" & $rowsort
    dbb()
    $aColCollect = _Excel_RangeRead($oWorkbook, Default, $oWorkbook.ActiveSheet.Usedrange.Columns($rowsort))
    $msg = "adding array"
    dbb()
    _ArrayAdd($aColUnique, _ArrayUnique($aColCollect, Default, Default, Default, $ARRAYUNIQUE_NOCOUNT), 0, "|", @CRLF, 1)
Next
$iRowT = UBound($aColCollect)
$msg = $iRowT & " total size"
dbb()

$aTmpArray0 = $aColUnique[0] ; setting temp0 arrays as the sub array0
$aTmpArray1 = $aColUnique[1] ;  setting temp1 array as the sub array1

;lets apply a filter once based on the first column to sort on (X:X)
For $u = 0 To UBound($aTmpArray0) - 1
    If $aTmpArray0[$u] = "" Then ContinueLoop; if filter value is blank then skip
    $i = 0
    $rowval = $aRowSort[$i]
    $rowsort = $rowval & ":" & $rowval
    $nCol1 = _Excel_ColumnToNumber($rowval)
    _Excel_FilterSet($oWorkbook, Default, Default, $nCol1, $aTmpArray0[$u])
    $msg = "first filter: " & $aTmpArray0[$u]
    dbb()
    ; lets apply the second filter to apply based on unique values contained in A:A
    For $j = 0 To UBound($aTmpArray1) - 1
        If $aTmpArray1[$j] = "" Then ContinueLoop ; if filter value is blank then skip
        $i = 1
        $rowval = $aRowSort[$i]
        $rowsort = $rowval & ":" & $rowval
        $nCol1 = _Excel_ColumnToNumber($rowval)
        _Excel_FilterSet($oWorkbook, Default, Default, $nCol1, $aTmpArray1[$j])
        $msg = "first filter: " & $aTmpArray1[$j]
        dbb()
        Local $afilter = _Excel_FilterGet($oWorkbook)
        If $afilter[0][6] <= 1 Then ; location of filtered row count, If the filter obtained no data, then skip
            $msg = "skipping loop"
            dbb()
            ContinueLoop
        EndIf
        $sName = @ScriptDir & "\R1_" & $aTmpArray0[$u] & "_score_" & $aTmpArray1[$j] & ".xls"
        $msg = "saving"
        dbb()
        MakeCopy(1, $iRowT, $sName) ; lets save the output as a xls
    Next
    _Excel_FilterSet($oWorkbook, Default, Default, 0)
Next


MsgBox(0, "completed", "Completed")
Exit

Func MakeCopy($iStart, $iEnd, $sName)
    Local $oRange = $oWorkbook.ActiveSheet.Range("A" & $iStart & ":X" & $iEnd)
    ;   Local $oRange = $oWorkbook.ActiveSheet.Range("A1:X"$iRowT&")
    Local $oWB = _Excel_BookNew($oExcel, 1)
    _Excel_RangeCopyPaste($oWB.ActiveSheet, $oRange, "A1")
    If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error copying cells." & "/" & @error)
    _Excel_BookSaveAs($oWB, $sName, $xlWorkbookNormal, True)
    If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error saving as" & "/" & @error)
    _Excel_BookClose($oWB, False)
EndFunc   ;==>MakeCopy


Func dbb()
    ;   MsgBox(0,$msg,$msg)
    ConsoleWrite($msg & @CRLF)
EndFunc   ;==>dbb

 

I did ask in this post how to deal best with the incremental variables and thus @subz suggested the subarrays; and therefore because of lack of foundational knowledge, I had to make the variables static for use in the nested loop. 

 

Working on this a little more....

HOWEVER, removing the _excel_filterget and the subsequent if statement reduced this to only 1.8mins, but of course I had a few dummy sheets I had to delete.

 

So changing the last function to this, stopped the excel sheets from being created with empty filter results, this took 1.9mins but avoided having blank exported files. 

......
    _Excel_RangeCopyPaste($oWB.ActiveSheet, $oRange, "A1")
    $oRangeRead = _Excel_RangeRead($oWB, Default, "A1:B3")
    $msg = "checking cell"
    dbb()
    ;_ArrayDisplay($oRangeRead, "$oRangeRead")
    If $oRangeRead[1][0] = "" Then
        $msg = "skipping sheet"
        dbb()
        Return
    EndIf
    $msg = "new book saving"
    dbb()
    If @error Then Exit MsgBox($MB_SYSTEMMODAL, "", "Error copying cells." & "/" & @error)
    .....

Thanks for your help, see what you think?

 

Edited by MrCheese
clearing time taken value as I had a msg box before it exit

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...