title: Column formatting from R to Excel (with package=xlsx), when you do not know column indices ahead of time (is there a better way)?
body: <p>I've been toying around with the xlsx package as a way of exporting output from R, and I'm having problems setting column data formats when you do not know (beforehand) what columns will be formatted which way.  </p>
  
  <p>As an aside, I found this most fantastic post on tradeblotter a huge help in getting me to this point.  I highly recommend it: <a href="http://tradeblotter.wordpress.com/2013/05/02/writing-from-r-to-excel-with-xlsx/" rel="nofollow">background post from Tradeblotter blog</a></p>
  
  <p>In my use case, I'm generating reports monthly, and each month the data.frame to be exported will increment by 1 or more columns (that then need to be formatted correctly).  I do not want to manually go in and set column names in the code, but would rather have R count the number of columns for me, then feed a vector of indices to the xlsx code.  </p>
  
  <p>After studying the structure of the colStyle list objects, I was able to create this workaround, but I have to believe that there is a better way, and I'm looking for some help in finding it.</p>
  
  <p>Thanks in advance!
  Chris</p>
  
  <pre><code>require(xlsx)
  iris$cost &lt;- rbinom(nrow(iris), 3, .85)+1000
  iris$cost2 &lt;- rbinom(nrow(iris), 3, .85)+1000
  test &lt;- createWorkbook()
  # Define some cell styles within that workbook
  csSheetTitle &lt;- CellStyle(test) + Font(test, heightInPoints=18, isBold=TRUE)
  csdollar &lt;- CellStyle(test, dataFormat=DataFormat("$###,##0.00")) # ... for ratio results
  csdefault &lt;- CellStyle(test, dataFormat=DataFormat("0.00")) # ... for ratio results
  csTableColNames &lt;- CellStyle(test) + Font(test, isBold=TRUE) + Alignment(wrapText=TRUE, h="ALIGN_CENTER") + Border(color="black", position=c("TOP", "BOTTOM"), pen=c("BORDER_THIN", "BORDER_THICK"))
  csTableColNames &lt;- CellStyle(test) + Font(test, isBold=TRUE) + Alignment(wrapText=TRUE, h="ALIGN_CENTER") + Border(color="black", position=c("TOP", "BOTTOM"), pen=c("BORDER_THIN", "BORDER_THICK"))
  sheet &lt;- createSheet(test, sheetName = names(ytddflist)[i])
  rows &lt;- createRow(sheet,rowIndex=1)
  sheetTitle &lt;- createCell(rows, colIndex=1)
  setCellValue(sheetTitle[[1,1]], "iris data with cost ($)")
  setCellStyle(sheetTitle[[1,1]], csSheetTitle)
  
  default.format = list(
    '1'=csdefault,
    '2'=csdefault,
    '3'=csdefault,
    '4'=csdefault)
  dollar.format =list(
    'notused'=csdollar)
  
  # here is where I create the dollar.format list object that will eventuall be fed to addDataFrame
  dollar.format.list &lt;- rep(dollar.format, 2)
  names(dollar.format.list) &lt;- as.character(c(6, 7))
  
  addDataFrame(iris, sheet, startRow=3, startColumn=1, colStyle=c(default.format,dollar.format.list), colnamesStyle = csTableColNames)
  
  saveWorkbook(test , "iriswithdollarx2.xlsx") 
  </code></pre>