*! Program to generate HTML code necessary to display a Stata dataset on the web
*! Author P. Wilner Jeanty
*! Date: February 17, 2013
program define dta2html
version 11
syntax [varlist(default=none)] [if] [in], SAVing(str) [css(str) TABTitle(str) PAGEtitle(str) Datalink(str) Todisp(str)]
marksample touse
tokenize "`saving'", parse(",")
args nameof_file secxx sav_opt
local nameof_file `nameof_file'.html
capture confirm new file `nameof_file'
if !_rc & "`sav_opt'" != "" & "`sav_opt'" != "replace" {
di as err "The suboption for {bf:saving()} must be {bf:replace}"
exit 198
}
else if _rc & "`sav_opt'"=="" confirm new file `nameof_file'
else if _rc & "`sav_opt'"!="" & "`sav_opt'" != "replace" {
di as err "The suboption for {bf:saving()} must be {bf:replace}"
exit 198
}
if "`imgsrc'"!="" & "`datalink'"=="" {
di as err "Option {bf:imgsrc()} must be combined with :bf:datalink()}"
exit 198
}
if "`todisp'"!="" {
tokenize "`todisp'", parse(",")
args todisnme secxx todisp_opt
if !inlist("`todisp_opt'", "txt", "img") {
di `"{err}The sub-option for {bf:todisp()} must be either "txt" or "img""'
exit 198
}
}
if "`pagetitle'"=="" local pagetitle "Stata Dataset in your Browser"
if "`tabtitle'"=="" local tabtitle "Stata Dataset"
tempname myhandle
local wrfile file write `myhandle'
local opfile file open `myhandle'
if "`if'"!="" local ifexp `if'
if "`in'"!="" local inexp `in'
local ifinexp `ifexp' `inexp'
preserve
if "`if'`in'"!="" qui keep `ifinexp'
capture drop `touse'
if "`varlist'"!="" local allvs `varlist'
else unab allvs: _all
gen Obs=_n
local allvs Obs `allvs'
local nvs : word count `allvs'
local outfile `"`nameof_file'"'
`opfile' using `"`outfile'"', w text `sav_opt'
set more off
`wrfile' _n
`wrfile' "" _n "
" _n
if `"`pagetitle'"' ~= "" {
`wrfile' `"`pagetitle'"' _n
}
`wrfile' `""' _newline
`wrfile' `""' _newline
if "`css'" == "" TableStyle, towr(`wrfile')
else `wrfile' `""' _newline
`wrfile' `""' _n
if "`css'"=="" `wrfile' `""' _n
else `wrfile' `""' _n // You might want to edit from here fit to your CSS need.
`wrfile' `""' _n
`wrfile' `"
"' _n
`wrfile' `""' _n
// Writing the values of the variables
`wrfile' `""' _n
local N=_N
forv i=1/`N' {
`wrfile' `"
"' _n
local j=1
foreach v of local allvs {
if `j'==1 {
`wrfile' `"
`=`v'[`i']'
"' _n
}
else {
cap confirm numeric var `v'
if !_rc `wrfile' `"
`=`v'[`i']'
"' _n
else `wrfile' `"
`=`v'[`i']'
"' _n
}
local ++j
}
`wrfile' `"
"' _n
}
`wrfile' `""' _n `"
"' _n `"
"' _n `"
"' _n
`wrfile' `" "' _n `"
"' _n `""' _n `""' _n
file close `myhandle'
set more off
restore
di _n `"Dataset written to HTML file {stata type `outfile':`c(pwd)'`c(dirsep)'`outfile'}"'
di _n `"To open in Internet Explorer, {browse "file:///`c(pwd)'`c(dirsep)'`outfile'":Click here}"'
end
// Defining the table style
program define TableStyle
version 11
syntax, towr(str)
`towr' `""' _n
end