RODBC fails: “invalid character value for cast specification” - Excel 2007

坚强是说给别人听的谎言 提交于 2021-01-27 03:53:54

问题


I'm trying to use RODBC to write to an Excel2007 file and I keep getting errors. I've reduced the issue to this very basic case, a 1-row data.frame with character, numeric, Date, and logical datatypes:

toWrite = data.frame( Name = "joe" , Date = as.Date("2011-01-01"), Value = 2 , Paid = FALSE )
xlFile = odbcConnectExcel2007( "REPLACE_WITH_XLSB_FILE_PATH" , readOnly = FALSE )
sqlSave( xlFile , toWrite , tablename = "worksheet1" , rownames = FALSE )

The error:

Error in sqlSave(xlFile, toWrite, tablename = "worksheet1", rownames = FALSE) : 
  [RODBC] Failed exec in Update
22018 39 [Microsoft][ODBC Excel Driver]Invalid character value for cast specification 
In addition: Warning message:
In odbcUpdate(channel, query, mydata, coldata[m, ], test = test,  :
  character data 'FALSE' truncated to 1 bytes in column 'Paid'

If I convert both the Date and logical columns to character then everything works fine. The issue is that these are now characters in Excel and can't be used as the intended data-types without conversion. I dug into the sqlSave code and it seems to be doing the right things. Has anyone else encountered this problem?


回答1:


For Anyone stumbling on this (5 years later), in R you can use the varTypes argument in sqlSave() like sqlSave(..., varTypes = c(somecolname="datetime", anothercolname= "datetime",...)).




回答2:


I also experienced the same issue today. I want update a table in R to SQL-serve. It gives me the exactly same error message. Then I changed all the "Date" type fields to "character" type. I updated again, it worked.

It seems that SQL-server cannot recognize "Date" type variable from R properly.




回答3:


I've heard of this problem before:

Workaround:

  • Use "0" for false,
  • Set Paid up as a text field
  • Change your application logic to use !=0 for True

I'll try and find you the bug ticket # for you to track




回答4:


closing this question. There doesn't seem to be a good fix aside from converting to character. I opted to write a command-line program that writes the data to a temporary CSV file, opens Excel, and imports the CSV.



来源:https://stackoverflow.com/questions/7779832/rodbc-fails-invalid-character-value-for-cast-specification-excel-2007

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!