从数据集生成在 Excel 2002 或 Excel 2003 中使用的 XML .NET

using System.Data.OleDb;
using System.Xml;
private string strConn ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ " C:\\Program Files\\Microsoft Office\\Office10\\Samples\\"
+ "Northwind.mdb;";
button1_Click 处理程序中添加以下代码:
//Connect to the data source.
         OleDbConnection objConn = new OleDbConnection (strConn);
         try
         {
            objConn.Open();

            //Fill a dataset with records from the Customers table.
            OleDbCommand objCmd = new OleDbCommand(
               "Select CustomerID, CompanyName, ContactName, "
               + "Country, Phone from Customers", objConn);
            OleDbDataAdapter objAdapter = new OleDbDataAdapter();
            objAdapter.SelectCommand = objCmd;
            DataSet objDataset = new DataSet();
            objAdapter.Fill(objDataset);


            //Create the FileStream to write with.
            System.IO.FileStream fs = new System.IO.FileStream(
               "C:\\Customers.xml", System.IO.FileMode.Create);

            //Create an XmlTextWriter for the FileStream.
            System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(
               fs, System.Text.Encoding.Unicode);

            //Add processing instructions to the beginning of the XML file, one
            //of which indicates a style sheet.
            xtw.WriteProcessingInstruction("xml", "version='1.0'");
            //xtw.WriteProcessingInstruction("xml-stylesheet",
              // "type='text/xsl' href='customers.xsl'");

            //Write the XML from the dataset to the file.
            objDataset.WriteXml(xtw);
            xtw.Close();

            //Close the database connection.
            objConn.Close();
         }
         catch (System.Exception ex)
         {
            MessageBox.Show(ex.Message);
         }
关键部分在这里:需要注意
   System.IO.FileStream fs = new System.IO.FileStream( "C:\\Customers.xml", System.IO.FileMode.Create); 
   System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(fs, System.Text.Encoding.Unicode); 
   xtw.WriteProcessingInstruction("xml", "version='1.0'"); 
   objDataset.WriteXml(xtw); 
   xtw.Close();


posted @ 2004-12-22 09:53  jhtchina  阅读(614)  评论(0编辑  收藏  举报