在excel工作簿中使用interop抛出错误写长文本?

我正在写长文本(1K到2K字符长,普通的XML数据)到Excel工作簿中的单元格。 下面的语句抛出从HRESULT:0x800A03EC COM错误exception

range.set_Value(Type.Missing, data); 

如果我复制粘贴相同的XML手动到Excel中,它只是工作正常,但同样不能正常工作。 如果我把文字去掉像100/300字符这样的文字就可以了。

有一个限制(如果我没有记错的话,800到900个字符之间)几乎不可能这样。

尝试使用ole连接并使用SQL命令插入数据。 这可能对你更好。 那么你可以使用互操作来进行必要的格式化。

以下知识库文章解释说,最大限制是911个字符。 我检查了我的代码相同的工作,string达911字符。

http://support.microsoft.com/kb/818808

本文中提到的解决方法build议确保没有单元格保存超过911个字符。 这是跛脚!

良好的Ole和Excel的文章: http : //support.microsoft.com/kb/316934

下面的代码更新一个私有variables,它是成功的行数,并返回一个string,它是Excel文件的path。

记得从System.IO;使用Path System.IO;

string tempXlsFilePathName; string result = new string;

  string sheetName; string queryString; int successCounter; // set sheetName and queryString sheetName = "sheetName"; queryString = "CREATE TABLE " + sheetName + "([columnTitle] char(255))"; // Write .xls successCounter = 0; tempXlsFilePathName = (_tempXlsFilePath + @"\literalFilename.xls"); using (OleDbConnection connection = new OleDbConnection(GetConnectionString(tempXlsFilePathName))) { OleDbCommand command = new OleDbCommand(queryString, connection); connection.Open(); command.ExecuteNonQuery(); yourCollection.ForEach(dataItem=> { string SQL = "INSERT INTO [" + sheetName + "$] VALUES ('" + dataItem.ToString() + "')"; OleDbCommand updateCommand = new OleDbCommand(SQL, connection); updateCommand.ExecuteNonQuery(); successCounter++; } ); // update result with successfully written username filepath result = tempXlsFilePathName; } _successfulRowsCount = successCounter; return result; 

注意这是编辑匆忙,所以可能包含一些错误。

为了解决这个限制,一次只写入/更新一个单元格,并立即处理Excel com对象。 并重新创build该对象以写入/更新下一个单元格。

我可以证实这个解决scheme在VS2010(VB.NET项目)中使用Microsoft Excel 10.0对象库(Microsoft Office XP)

这个限制应该在Excel 2007/2010中被删除。 使用VBA下面的工作

 Sub longstr() Dim str1 As String Dim str2 As String Dim j As Long For j = 1 To 2000 str1 = str1 & "a" Next j Range("a1:a5").Value2 = str1 str2 = Range("a5").Value2 MsgBox Len(str2) End Sub 

我会开始说我自己没有尝试过,但是我的研究表明你可以使用QueryTable来克服911字符的限制。

这是我发现的主要文章,它讨论了如何使用logging集作为QueryTable的数据源并将其添加到电子表格中: http : //www.excelforum.com/showthread.php? t=556493&p=1695670&viewfull =1# post1695670 。

下面是使用QueryTables的一些示例C#代码: 使用C#(QueryTables.Add)中的excel interop导入txt文件 。