【问题标题】:Export Datagridview To XML File C#将 Datagridview 导出到 XML 文件 C#
【发布时间】:2020-05-04 21:51:50
【问题描述】:

我有一个要求,我需要将导入到“datagridview”的excel文件中的数据导出为指定格式“xml”,首先我从excel填充到datagrid并保存为Xml,遵循这段代码

        namespace SAMPLE_
        {


            public partial class Form1 : Form
            {
                public Form1()
                {
                    InitializeComponent();

                }

这里我是使用 Microsoft Office Interop Excel 导入 Excel 文件:

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application xlApp;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorlSheet;
            Microsoft.Office.Interop.Excel.Range xlRange;

            int xlRow;
            string strfileName;

            openFilalog1.Filter = "Excel Office | *.xls; *.xlsx";
            openFilalog1.ShowDialog();
            strfileName = openFilalog1.FileName;


             if(strfileName != string.Empty)
            {

                xlApp = new Microsoft.Office.Interop.Excel.Application();
                xlWorkBook = xlApp.Workbooks.Open(strfileName);
                xlWorlSheet = xlWorkBook.Worksheets["SHEET1"];
                xlRange = xlWorlSheet.UsedRange;
                int i=0;
                for (xlRow = 2; xlRow <= xlRange.Rows.Count; xlRow++)
                {
                    if(xlRange.Cells[xlRow,2].Text != "")
                    {
                        i++;
                        dataGridView1.Rows.Add(i, xlRange.Cells[xlRow, 1].Text, xlRange.Cells[xlRow, 
                        2].Text,
                        xlRange.Cells[xlRow, 3].Text, xlRange.Cells[xlRow, 4].Text,
                        xlRange.Cells[xlRow, 5].Text, xlRange.Cells[xlRow, 6].Text,
                        xlRange.Cells[xlRow, 7].Text, xlRange.Cells[xlRow, 8].Text,
                        xlRange.Cells[xlRow, 9].Text,xlRange.Cells[xlRow, 10].Text,
                        xlRange.Cells[xlRow, 11].Text,xlRange.Cells[xlRow, 12].Text,
                        xlRange.Cells[xlRow, 13].Text);

                    }

            }
                xlWorkBook.Close();
                xlApp.Quit();

            }

这是我用来导出的按钮:

       private void button1_Click(object sender, EventArgs e)
                    {
                        DataSet ds = (DataSet)dataGridView1.DataSource;
                        SaveFilalog sfd = new SaveFilalog();
                        sfd.Filter = "SHEET1|*.xml";
                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            try
                            {
                                ds.Tables[0].WriteXml(sfd.FileName);
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine(ex);
                            }
                        }
                    }

                    private void button2_Click(object sender, EventArgs e)
                    {

                    }
                }


            }

【问题讨论】:

  • 我需要知道xml格式。显然当前写入 ds.Tables[0].WriteXml(sfd.FileName);格式不正确。
  • 那么正确的格式是什么?
  • 你必须告诉我。您说“以指定格式'xml”。那么格式是什么?
  • 这是我想要的输出 xml 格式:&lt;rd&gt; &lt;id&gt;column 1 cell 1&lt;/id&gt; &lt;name&gt;column 2 cell 1&lt;/name&gt; &lt;last&gt;column 3 cell 1&lt;/last&gt; &lt;phone&gt;column 4 cell 1&lt;/phone&gt; &lt;refF&gt; &lt;adresse&gt;column 5 cell 1&lt;/adresse&gt; &lt;citie&gt;column 6 cell 1&lt;/citie&gt; &lt;/refF&gt; &lt;age&gt;column 7 cell 1&lt;/age&gt; &lt;mp&gt; &lt;degree&gt;column 8 cell 1&lt;/degree&gt; &lt;/mp&gt; &lt;dpa&gt;column 9 cell 1&lt;/dpa&gt; &lt;/rd&gt;

标签: c# excel xml


【解决方案1】:

从数据表中它会是这样的

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(string));
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("last", typeof(string));
            dt.Columns.Add("phone", typeof(string));
            dt.Columns.Add("adresse", typeof(string));
            dt.Columns.Add("citie", typeof(string));
            dt.Columns.Add("age", typeof(string));
            dt.Columns.Add("mp", typeof(string));
            dt.Columns.Add("dpa", typeof(string));
            dt.Columns.Add("New A", typeof(string));
            dt.Columns.Add("New B", typeof(string));
            dt.Columns.Add("New C", typeof(string));
            dt.Columns.Add("New D", typeof(string));
            for (xlRow = 2; xlRow <= xlRange.Rows.Count; xlRow++)
            {
                if (xlRange.Cells[xlRow, 2].Text != "")
                {

                    dt.Rows.Add(new object[] {
                        xlRange.Cells[xlRow, 1].Text, 
                        xlRange.Cells[xlRow,2].Text,
                        xlRange.Cells[xlRow, 3].Text, xlRange.Cells[xlRow, 4].Text,
                        xlRange.Cells[xlRow, 5].Text, xlRange.Cells[xlRow, 6].Text,
                        xlRange.Cells[xlRow, 7].Text, xlRange.Cells[xlRow, 8].Text,
                        xlRange.Cells[xlRow, 9].Text, xlRange.Cells[xlRow, 10].Text,
                        xlRange.Cells[xlRow, 11].Text, xlRange.Cells[xlRow, 12].Text,
                        xlRange.Cells[xlRow, 13].Text
                    });

                }
            }
            dataGridView1.DataSource = dt;


            string header = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><Sheet1></Sheet1>";
            XDocument doc = XDocument.Parse(header);
            XElement sheet1 = doc.Root;

            foreach (DataRow row in dt.AsEnumerable())
            {
                XElement rd = new XElement("rd", new object[] {
                    new XElement("id", row["id"]),
                    new XElement("name", row["name"]),
                    new XElement("last", row["last"]),
                    new XElement("phone", row["phone"]),
                    new XElement("refF", new object[] {
                        new XElement("adresse", row["adresse"]),
                        new XElement("citie", row["citie"]),
                    }),
                    new XElement("age", row["age"]),
                    new XElement("mp", new XElement("degree", row["mp"])),
                    new XElement("dpa", row["dpa"])
                });

                sheet1.Add(rd);
            }

            doc.Save(FILENAME);

        }

    }

}

【讨论】:

  • 调试后发现这个问题: System.NullReferenceException: 对象引用未定义到对象的实例。到 C:\Users\Ysf\Documents\Visual Studio 2015\Projects\SAMPLE\SAMPLE\Form1.cs 中的 SAMPLE.Form1.button1_Click (Object sender, EventArgs e):第 129 行第 129 行 = ds.Tables[0].WriteXml (save.FileName);
  • DataGridView 并不总是有 DataSource。您可以像在代码中那样手动加载 DGV,而无需数据源。所以DataSet ds = (DataSet)dataGridView1.DataSource;数据源为空。
  • 那么作为导出按钮的代码我应该怎么做?
  • 您必须做出选择 1) 不要将数据直接放入 DGV 中,而是将数据放入 datartable。使表成为 DGV 的数据源,因此我的代码可以工作 2) 更改我的代码以直接从 DGV 而不是从表中获取数据。
  • 如何更改您的代码以直接从 DGV 获取数据?
猜你喜欢
  • 1970-01-01
  • 2017-08-20
  • 2019-04-18
  • 2014-04-09
  • 2012-04-14
  • 1970-01-01
  • 1970-01-01
  • 2012-02-22
  • 1970-01-01
相关资源
最近更新 更多