mcaceresb / stata-gtools

Faster implementation of Stata's collapse, reshape, xtile, egen, isid, and more using C plugins
https://gtools.readthedocs.io
MIT License
182 stars 38 forks source link

Export results to word or excel #89

Closed oerdem19 closed 1 year ago

oerdem19 commented 1 year ago

What would you like gtools to add or change (and why)? Option to Export results to excel or word. Thank you.

mcaceresb commented 1 year ago

@oerdem19 This is not something that is within the purview of gtools. There are existing Stata tools to do this for various formats; if you have a specific use case I might be able to provide some guidance but I wouldn't add it to gtools directly.

oerdem19 commented 1 year ago

Thank you.

mcaceresb commented 1 year ago

@oerdem19 I didn't realize this was somewhat cumbersome; I don't use gstats like this but I figured I might as well code something to help. Please upgrade to the latest version 1.10.2 in the develop branch.

capture program drop _gstats_excel
program _gstats_excel
    syntax namelist(min=1 max=1) using/, [sheet(str) replace]
    if "`sheet'" == "" local sheet `namelist'
    mata _gstats_excel(`namelist', `"`using'"', `"`sheet'"', "`replace'" != "")
    * mata xlUsing = `"`using'"'
    * mata xlSheet = `"`sheet'"'
end

cap mata mata drop _gstats_excel()
mata
void function _gstats_excel(
    class GtoolsResults scalar GstatsOutput,
    string scalar xlUsing,
    string scalar xlSheet,
    real scalar replace)
{
    class xl scalar xlWb
    string vector xlSheets

    xlWb = xl()
    if ( fileexists(xlUsing) ) {
        xlWb.load_book(xlUsing)
        xlSheets = xlWb.get_sheets()
        if ( any(xlSheet :== xlSheets) & replace ) {
            xlWb.clear_sheet(xlSheet)
        }
        else if ( any(xlSheet :== xlSheets) ) {
            errprintf("'%s' already in workbook '%s' with no replace\n", xlSheet, xlUsing)
            _error(198)
        }
        else {
            xlWb.add_sheet(xlSheet)
        }
    }
    else {
        xlWb.create_book(xlUsing, xlSheet)
        xlSheets = xlWb.get_sheets()
    }

    xlWb.set_sheet(xlSheet)
    xlWb.put_string(1, 1, GstatsOutput.formatOutput())
    xlWb.close_book()
}
end

sysuse auto, clear
gstats tab price mpg, by(foreign rep78) mata
* mata GstatsOutput.formatOutput()
_gstats_excel GstatsOutput using gtools-excel.xlsx, replace
oerdem19 commented 1 year ago

Thank you very much. I think this can help many others too. Your program is very efficient and fast.