c# - 在 C# 中解析 Excel 文件时,单元格似乎在 255 个字符处被截断......我该如何阻止它?

标签 c# linq excel excel-2007 xlsx

我正在使用 c# 在 asp.net 中解析上传的 excel 文件 (xlsx)。我正在使用以下代码(已简化):

string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\";");
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connString);
DataSet ds = new DataSet();
adapter.Fill(ds);
adapter.Dispose();
DataTable dt = ds.Tables[0];
var rows = from p in dt.AsEnumerable() select new { desc = p[2] };

这非常有效,但是如果单元格中的任何字符超过 255 个,它就会被截断。知道我做错了什么吗?谢谢。

编辑:查看 Excel 表格时,它显示的字符数远远超过 255 个,所以我认为表格本身没有限制。

最佳答案

解决方案!

我今天也一直在与此作斗争。在解析 Excel 电子表格之前,我终于通过修改一些注册表项使其正常工作。

您必须在解析 Excel 电子表格之前更新此注册表项:

// Excel 2010
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\14.0\Access Connectivity Engine\Engines\Excel\
or
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Office\14.0\Access Connectivity Engine\Engines\Excel\

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

// Excel 2003
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel\

将此键下的 TypeGuessRows 更改为 0 并将 ImportMixedTypes 更改为 Text。您还需要更新连接字符串以在扩展属性中包含 IMEX=1:

string connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";");

引用资料

http://blogs.vertigo.com/personal/aanttila/Blog/archive/2008/03/28/excel-and-csv-reference.aspx

http://msdn.microsoft.com/en-us/library/ms141683.aspx

...characters may be truncated. To import data from a memo column without truncation, you must make sure that the memo column in at least one of the sampled rows contains a value longer than 255 characters, or you must increase the number of rows sampled by the driver to include such a row. You can increase the number of rows sampled by increasing the value of TypeGuessRows under the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Excel registry key....

关于c# - 在 C# 中解析 Excel 文件时,单元格似乎在 255 个字符处被截断......我该如何阻止它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/926453/

相关文章:

python - 通过 Excel/VBA 运行 Python 脚本

c# - Unity - 如何使用 Sprite 渲染器制作圆形进度条?

c# - 使用xml删除书签

c# - Visual Studio 单元测试代码覆盖异常 "file path of .coverage file is invalid or corrupt"

c# - 无法在 Windows 10 移动版上部署

c# - 是否有用于获取字符串列表中最长字符串的 LINQ 函数?

c# - 使用Linq从字典中过滤掉某些键并返回一个新字典

.net - 您遇到的最令人印象深刻的 LINQ 语句是什么?

excel - 在 VBA (Excel) 中以编程方式添加组合框

正则表达式从字符串中提取第一组数字