简体   繁体   中英

How do I programmatically insert XML into an Excel worksheet?

I'm using an OleDbConnection to write some data to a spreadsheet. Several columns of this data include XML (not the data within the XML, but the XML itself). When I attempt to insert using ExecuteNonQuery(), however, I receive the following OleDbException: Syntax error (missing operator) in query expression '""'

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.

For example, in C#, to pass a " character to a literal string, you need to use:

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. However, SQL will treat these as quotation operators, and not quotation literals, unless you use the escape sequence:

""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.

Assuming that the escape sequence for a " character is a double set of quotes "" on your SQL implementation, try using something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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