简体   繁体   English

如何以编程方式将XML插入Excel工作表中?

[英]How do I programmatically insert XML into an Excel worksheet?

I'm using an OleDbConnection to write some data to a spreadsheet. 我正在使用OleDbConnection将一些数据写入电子表格。 Several columns of this data include XML (not the data within the XML, but the XML itself). 此数据的几列包括XML(不是XML内的数据,而是XML本身)。 When I attempt to insert using ExecuteNonQuery(), however, I receive the following OleDbException: Syntax error (missing operator) in query expression '""' 但是,当我尝试使用ExecuteNonQuery()进行插入时,我收到以下OleDbException:查询表达式'“”'中的语法错误(缺少运算符)

Most recently, I've tried something something like 最近,我尝试过类似

...
command.CommandText = "INSERT INTO (Column1) VALUES(""<MyElement name="Name"/>"")";

to do this. 去做这个。 It seems as though the quotation marks around "Name" are what's throwing everything off. 好像“名称”两边的引号引起了一切。

Thanks in advance for any help. 在此先感谢您的帮助。

You must use escape characters to express your quotation characters as literal quotations and not as operations. 您必须使用转义字符将引号字符表示为文字引号而不是操作。 It may get tricky as there are escape characters in C#, and escape characters in SQL as well. 由于C#中有转义字符,SQL中也有转义字符,因此可能会比较棘手。

For example, in C#, to pass a " character to a literal string, you need to use: 例如,在C#中,要将“”字符传递给文字字符串,您需要使用:

string quoted = "\\"Quoted String\\"";

Evaluating the string quoted will return "Quoted String" (including quotes) 计算带引号的字符串将返回“带引号的字符串” (包括引号)

This will allow you to pass the quotes into the SQL command. 这将允许您将引号传递到SQL命令中。 However, SQL will treat these as quotation operators, and not quotation literals, unless you use the escape sequence: 但是,除非您使用转义序列,否则SQL会将它们视为引号运算符,而不是引号文字。

""Quoted String""

So for every quote character you want to use as part of a literal in a SQL statement, you must enter the character twice. 因此,对于要在SQL语句中用作文字一部分的每个引号字符,必须输入两次。

Assuming that the escape sequence for a " character is a double set of quotes "" on your SQL implementation, try using something like this: 假设在您的SQL实现中,“字符”的转义序列是双引号“”,请尝试使用以下命令:

command.CommandText = "INSERT INTO (Column1) VALUES(\\"<MyElement name=\\"\\"Name\\"\\"/>\\")";

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

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