我有一个字符串,需要按原样以XLS格式保存,但是WriteXLS
函数似乎总是转换为数字。手动打开xls时也会出现该错误。我该如何解决?
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
预期结果:92343E102
如果可能的话,我需要在没有安装python的情况下这样做,所以dataframes2xls
对我来说不是一个选择-无论如何都请尝试一下
答案 0 :(得分:2)
安装writexl软件包:
install.packages("devtools", dependencies=TRUE)
# devtools has a _lot_ of dependencies
# it also has a bunch of system tool requirements
devtools::install_github("ropensci/writexl")
#make a copy of iris
tmp <- iris
# set [1,1] to your string:
tmp[1,1] <- "92343E102" # makes that column 'character'
tmp2 <- writexl::write_xlsx(tmp)
readxl::read_xlsx(tmp2)
# A tibble: 150 x 5
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
<chr> <dbl> <dbl> <dbl> <chr>
1 92343E102 3.5 1.4 0.2 setosa
2 4.9 3 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5 3.4 1.5 0.2 setosa
9 4.4 2.9 1.4 0.2 setosa
10 4.9 3.1 1.5 0.1 setosa
# ... with 140 more rows
答案 1 :(得分:1)
我建议您改用dataframes2xls::write.xls()
:
# Make a sample dataframe:
nb <- data.frame(A = "92343E102", B = 92343E102, stringsAsFactors = F)
WriteXLS::WriteXLS(nb, "testdf.xls") # Write out using WriteXLS() ...
readxl::read_xls("testdf.xls") # Doesn't work, per your post
#> # A tibble: 1 x 2
#> A B
#> <dbl> <dbl>
#> 1 9.23e106 9.23e106
# Maybe we can specify what kind of column it is when reading in the data?
readxl::read_xls("testdf.xls", col_types = "text")
# Still doesn't work, it must be the writer
#> # A tibble: 1 x 2
#> A B
#> <chr> <chr>
#> 1 -2147483648 -2147483648
dataframes2xls::write.xls(nb, "testdf2.xls") # So, try a different writer
readxl::read_xls("testdf2.xls")#, col_types = "text") # Works!
#> # A tibble: 1 x 2
#> A B
#> <chr> <dbl>
#> 1 "\"92343E102\"" 9.23e106
由reprex package(v0.2.1)于2018-11-02创建
答案 2 :(得分:1)
如果可以将其另存为csv,请在Excel中将其打开。一种选择是使用“数据”选项卡上的“从文本向导获取外部数据”。然后选择您的csv文件,配置适当的选项,然后在向导的第三步中,在其中包含文本的列上选择“导入为文本”,如下图所示。然后,您可以将其另存为.xls,然后再次打开它,而Excel不会将数据类型更改为科学数据。
答案 3 :(得分:0)
好吧,我终于找到了一种避免XLS将字符串“ 12E123”转换为科学型double的方法,该方法不需要使用XLConnect
进行excel交互
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
结果:
> 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
当然,由于我只有32位的JAVA工作,因此我可能必须切换到R32或编写32位R例程以正确保存我的XLS文件。
一次做一件事...希望这对某人有帮助