您的位置:首页 > 编程语言 > C#

C# 使用oledb导出excel,字段内容超长的解决方法

2013-05-28 16:26 806 查看
使用oledb导出excel时,如果某个字段内容长度超过255个字符,会报如下错误:

The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data.

 

代码如下:

var connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\test.xlsx;Extended Properties=\"Excel 12.0 XML;HDR=Yes;IMEX=0;CharacterSet=utf-8\";";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();

OleDbCommand com = new OleDbCommand();
com.Connection = conn;
com.CommandText = "CREATE TABLE [Report]([ID] Text,[Msg] Text)";
com.ExecuteNonQuery();
var msg = "a".PadRight(255,'b');com.CommandText = "INSERT INTO [Report$]([ID], [Msg]) VALUES(1,'"
+ msg
+ "')";
com.ExecuteNonQuery();
conn.Close();

如何解决这个问题呢?

1. 在excel 2007以前是可以直接定义 Memo 类型来解决这个问题的,当然2007以前使用的连接串是不一样的:
com.CommandText = "CREATE TABLE [Report]([Msg] Memo)";
2. 但是在excel 2007以后,这样就不可以了,但奇怪的是可以使用Alter来创建新列,新列可以识别出Memo类型!

创建表:

OleDbCommand com = new OleDbCommand();
com.Connection = conn;
com.CommandText = "CREATE TABLE [Report]([ID] Text)";
com.ExecuteNonQuery();

添加新列:
com.CommandText = "Alter Table [Report$] ADD [Msg] Memo";
com.ExecuteNonQuery();
然后插入数据:

var msg = "a".PadRight(255,'b');
com.CommandText = "INSERT INTO [Report$]([ID], [Msg]) VALUES(1,'"
+ msg
+ "')";
com.ExecuteNonQuery();

3. 还有种莫名其妙的方法:在创建表(Create)之后,Insert 的时候表名后不加 $

var msg = "a".PadRight(255,'b');
com.CommandText = "INSERT INTO [Report]([ID], [Msg]) VALUES(1,'"
+ msg
+ "')";
com.ExecuteNonQuery();

问题貌似解决了,但貌似而已,还是有问题的。

以上的Create和Insert是在同一次操作中,如果第一次创建了一个excel,但插入的数据中,长度没有超过255字符的,那么在下一次Insert时,

恭喜你:此问题又来了!

怎么办呢?

请看终极解决办法:

在Create后,第一次Insert时,如果列[Msg]长度小于255,后边补空格使其长度超过255.

var msg = "a".PadRight(256,' ');
com.CommandText = "INSERT INTO [Report$]([ID], [Msg]) VALUES(1,'"
+ msg
+ "')";
com.ExecuteNonQuery();

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐