Search code examples
rxlsxxls

Wrong format saving XLS files: automatic conversion to numbers


I have a string that I need to save as-is in XLS format, but the WriteXLS function seems to always convert to a number. The error is also present when opening the xls manually. How can I fix this?

nb <- data.frame("92343E102", stringsAsFactors = F)
WriteXLS::WriteXLS(nb, "testdf.xls")
readxl::read_xls("testdf.xls")
> read_xls("testdf.xls")
# A tibble: 1 x 1
  X.92343E102.
         <dbl>
1     9.23e106

Expected result: 92343E102

I would need to do so without having python installed if possible, so dataframes2xls is not an option for me - appreciate the attemp anyway


Solution

  • Ok finally I think found a way to avoid XLS conversion of strings like "12E123" to scientific double, which requires no excel interaction using XLConnect

    nb <- data.frame(as.character('92343E102'), stringsAsFactors = F)
    WriteXLS::WriteXLS(nb, "testdf.xls")
    readxl::read_xls("testdf.xls")
    wb <- XLConnect::loadWorkbook("testdf.xls")
    XLConnect::createSheet(wb, name="newsheet")
    XLConnect::writeWorksheet(wb, nb, sheet = "newsheet")
    XLConnect::saveWorkbook(wb)
    readxl::read_xls("testdf.xls", sheet=1) #converted string to wrong number
    readxl::read_xls("testdf.xls", sheet=2) # success! string stays string
    

    result:

    > readxl::read_xls("testdf.xls", sheet=1)
    # A tibble: 1 x 1
      as.character..92343E102..
                          <dbl>
    1                  9.23e106
    > readxl::read_xls("testdf.xls", sheet=2)
    # A tibble: 1 x 1
      as.character..92343E102..
      <chr>                    
    1 92343E102                
    

    Of course since I only have 32bit JAVA at work I might have to switch to R32 for this, or write 32bit-R routines to correctly save my XLS files..

    One thing at a time... Hope this helps someone