简体   繁体   English

使用C#/ OLEDB从Excel导入时值更改

[英]Values changing when importing from Excel with C#/OLEDB

I'm trying to import some data from an Excel spreadsheet into my C# application using OleDB. 我正在尝试使用OleDB将一些数据从Excel电子表格导入到C#应用程序中。 I use the standard connection string with the IMEX=1,HDR=YES options 我将标准连接字符串与IMEX=1,HDR=YES选项一起使用

Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties="Excel 12.0;HDR=YES;IMEX=1" Provider = Microsoft.ACE.OLEDB.12.0;数据源= {0};扩展属性=“ Excel 12.0; HDR = YES; IMEX = 1”

I have a column where the values are mostly the text: TRUE or FALSE. 我有一列的值主要是文本:TRUE或FALSE。 Partway down there is a couple of values of BLANK. 在途中,有两个BLANK值。 When the import happens, the BLANK values are replaced empty strings. 导入时,将BLANK值替换为空字符串。 This is presumably because OleDB determined the data type of the column to be boolean and doesn't import any non-boolean values, like BLANK. 据推测,这是因为OleDB确定列的数据类型为布尔型,并且不导入任何非布尔值,例如BLANK。

I tried the solution in this answer but it did not work. 我尝试了此答案中的解决方案,但没有成功。 Even when I pre-create the DataTable and set its columns to all have a datatype of string, the BLANK values continue to be removed. 即使当我预先创建DataTable并将其列都设置为具有字符串数据类型时,BLANK值仍会继续被删除。

I have tried hacking the registry key suggested in the same question but to no effect. 我曾尝试破解同一问题中建议的注册表项,但没有任何效果。

Is there any recourse? 有没有追索权? Or am I going to have to try to use COM? 还是我将不得不尝试使用COM? We don't have the budget for SpreadsheetGear and I can't use excellibrary because I have to deal with .xlsx files mostly. 我们没有SpreadsheetGear的预算,因为我必须主要处理.xlsx文件,所以我不能使用Execbrary

Thanks in advance 提前致谢

I know I am three years late, but this might help somebody. 我知道我迟到了三年,但这可能会对某人有所帮助。 All credit goes to Andrew Garrison who posted his answer here . 一切归功于安德鲁加里森( Andrew Garrison) ,他在这里发表了答案。 You need to modify a registry setting: 您需要修改注册表设置:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\12.0\Access Connectivity Engine\Engines\Excel\

Change TypeGuessRows to 0 and ImportMixedTypes to Text under this key. 在此键下,将TypeGuessRows更改为0 ,将ImportMixedTypes更改为Text

ACE scans first 8 rows and tries to guess column formats. ACE扫描前8行,并尝试猜测列格式。 Everything else that doesn't match the format afterwards returns as NULL. 之后,所有其他与格式不匹配的内容都将返回NULL。 Setting TypeGuessRow to 0 forces the driver to scan all rows to determine format (of course there is some performance hit). 将TypeGuessRow设置为0会强制驱动程序扫描所有行以确定格式(当然会影响性能)。 ImportMixedTypes=text specifies that columns with mixed format, as in your case, should be imported as text. ImportMixedTypes = text指定应将混合格式的列(如您的情况)导入为文本。

尝试将Excel文件保存为CSV格式并进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM