c#当string数据超过255个字符时,错误插入Excel

我正试图导出一些数据到Excel。 我正在使用OLEDB 12.连接string看起来像:

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;'" 

我使用INSERT查询。 但是,只要目标列中的数据超过255个字符,就会发生exception。

 Exception Details: System.Data.OleDb.OleDbException: The field is too small to accept the amount of data you attempted to add. Try inserting or pasting less data. 

在SO上有一个类似的post: Excel无法插入超过255个字符? 但是它并没有进入c#,

我也提到http://support.microsoft.com/kb/213841并没有得到任何解决scheme。

请帮忙。

我最初以为你可能能够在写入数据之前定义单元格的数据types(备忘录/文本),但是这从这篇文章中看不出来是可能的http://support.microsoft.com/kb/278973大约一半的时候,明确指出在excel中定义数据types是不可能的。)

我所能提供的“最佳”解决scheme是将数据切分成255个字符,并将它们插入到excel文件中,并放入nieghbouring列中。 从那里你可以使用一些优秀的互操作性将它们拼接在一起。

我最后做了什么:

由于我无法积累足够的答复,并且无法解决问题,所以我切换到Excel对象(Office Interop),现在没有问题了。

尝试使用此代码,可能会帮助

  public static void DataSetsToExcel(DataSet dataSet, string filepath) { try { string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=Excel 12.0 Xml;"; string tablename = ""; DataTable dt = new DataTable(); foreach (System.Data.DataTable dataTable in dataSet.Tables) { dt = dataTable; tablename = dataTable.TableName; using (OleDbConnection con = new OleDbConnection(connString)) { con.Open(); StringBuilder strSQL = new StringBuilder(); strSQL.Append("CREATE TABLE ").Append("[" + tablename + "]"); strSQL.Append("("); for (int i = 0; i < dt.Columns.Count; i++) { strSQL.Append("[" + dt.Columns[i].ColumnName + "] text,"); } strSQL = strSQL.Remove(strSQL.Length - 1, 1); strSQL.Append(")"); OleDbCommand cmd = new OleDbCommand(strSQL.ToString(), con); cmd.ExecuteNonQuery(); for (int i = 0; i < dt.Rows.Count; i++) { strSQL.Clear(); StringBuilder strfield = new StringBuilder(); StringBuilder strvalue = new StringBuilder(); for (int j = 0; j < dt.Columns.Count; j++) { strfield.Append("[" + dt.Columns[j].ColumnName + "]"); strvalue.Append("'" + dt.Rows[i][j].ToString().Replace("'", "''") + "'"); if (j != dt.Columns.Count - 1) { strfield.Append(","); strvalue.Append(","); } else { } } if (strvalue.ToString().Contains("<br/>")) { strvalue = strvalue.Replace("<br/>", Environment.NewLine); } cmd.CommandText = strSQL.Append(" insert into [" + tablename + "]( ") .Append(strfield.ToString()) .Append(") values (").Append(strvalue).Append(")").ToString(); cmd.ExecuteNonQuery(); } con.Close(); } } } catch (Exception ex) { } }