C# 读取XML格式的Excel文件

除了这种操作方式,还可以参考:C#使用EPPlus操作Excel(读写)

以前项目中会在Excel中配置参数后,加载动态显示到界面中,动态显示参考我的文章:C# 使用FlowLayoutPanel动态显示_花开莫与流年错_的博客-CSDN博客

首先呢,需要将文件保存为XML格式(另存为时选择如下):

1、文件内容是用Excel来配置的,我的如下咯

2、之后呢,来点实例代码,看下我写好的对象怎么用哈

        static void Main(string[] args)
        {
            //GetSocket socket = new GetSocket();
            //socket.test();
            MyXML xml = new MyXML("test.xml", "Sheet1");
            List<string> list = new List<string>();
            if (0 < xml.ReadExcelRow(list, 1))
                MessageBox.Show("参数读取错误");
            int i = 0;
            Console.WriteLine("第一行参数如下");
            for (; i < list.Count - 1; i++)
                Console.Write(list[i] + ", ");
            Console.WriteLine(list[i]);

            Console.WriteLine("第一列参数如下");
            List<string> column = new List<string>();
            if (0 < xml.ReadExcelColumn(column, 1))
                MessageBox.Show("参数读取错误");
            i = 0;
            for (; i < column.Count - 1; i++)
                Console.Write(column[i] + ", ");
            Console.WriteLine(column[i]);

            Console.Read();
        }

3、那么运行会出现怎样的效果呢,如下咯

4、然后呢,是如何实现读取表格参数呢,我这里呢读取一行和读取所有:

using System;
using System.Collections.Generic;
using System.Linq;

using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;

class MyXML
{
    bool debug = false;

    /// <summary>
    /// 读取某行数据
    /// </summary>
    /// <param name="neadList">要返回的链表,默认已string格式保存</param>
    /// <param name="fileName">打开的文件名</param>
    /// <param name="sheetName">需要的表格名</param>
    /// <param name="needRow">第几行</param>
    /// <returns></returns>
    public int ReadExcelRow(List<string> neadList, string fileName, string sheetName, int needRow)
    {
        needRow--;      // 内部默认从0开始计算,
        XElement element = null;
        try
        {
            element = XElement.Load(@fileName);
        }
        catch
        {
            MessageBox.Show("加载文件失败");
            return 3;
        }
        //IEnumerable<string> Rows = from item in element.Elements("Sheet1")
        //                           select (string)item.Attribute("Row");
        List<XElement> sheet = element.Elements().ToList();

        if (debug)
        {
            Console.WriteLine(sheet.Count());
            //IEnumerable<XElement> childData = from item in element.Elements()
            //                                  select item.Element("Worksheet");
            //Console.WriteLine(childData.Count());
            //foreach (string str in childData)
            //    Console.WriteLine(str);
            for(int i = 0; i < sheet.Count; i++)
            {
                Console.WriteLine(sheet[i].Name + "\r\n");
                string name = sheet[i].Name.ToString();
                if (name.Contains("Worksheet"))
                {
                    // 显示定义标识符名字
                    Console.WriteLine(name);
                    // 显示标识符里面属性设定
                    Console.WriteLine(sheet[i].FirstAttribute);         // 读取第一个标注属性
                    Console.WriteLine(sheet[i].LastAttribute);          // 读取最后一个个标注属性
                    Console.WriteLine(sheet[i].Attributes("Name"));     // bug,并不知道干嘛的
                    Console.WriteLine(GetValue(sheet[i].FirstAttribute.ToString(), "\"", "\""));
                }
            }
        }
        
        bool haveNeedTable = false;
        for(int i = 0; i < sheet.Count; i++)
        {

            string name = sheet[i].Name.ToString();
            // 确定是表格内容(Sheet)
            if (name.Contains("Worksheet"))
            {
                string str = GetValue(sheet[i].FirstAttribute.ToString(), "\"", "\"");
                // 有需要的Sheet
                if (sheetName == str)
                {
                    haveNeedTable = true;
                    List<XElement> listInSheet = sheet[i].Elements().ToList();
                    List<XElement> Rows = listInSheet[0].Elements().ToList();
                    for(int m = 0; m < Rows.Count; m++)
                    {
                        string row = Rows[m].Name.ToString();
                        if (debug)
                            Console.WriteLine("确定这行是什么:" + row);
                        // 确定是表格内容(Sheet)
                        if (!row.Contains("Row"))
                        {
                            Rows.RemoveAt(m);
                            m--;
                        }
                    }

                    if (debug)
                    {
                        Console.WriteLine("读取到需要的Sheet了");
                        Console.WriteLine(sheet[i].Value);                              // 显示里面需要读取的值
                        Console.WriteLine("总的有:" + Rows.Count() + "行数据");
                        for (int j = 0; j < Rows.Count; j++)
                        {
                            Console.WriteLine("读取到的如下有如下一行:");
                            Console.WriteLine(Rows[j]);
                        }
                    }

                    // 如果读取的行数大于所有行数报错输出
                    if (needRow > Rows.Count)
                    {
                        if (debug)
                            Console.WriteLine("请求错误:Sheet中没有这么多行数据");
                        return 2;
                    }

                    List<XElement> need = Rows[needRow].Elements().ToList();
                    int value = 0;
                    for (int j = 0; j < need.Count; j++)
                    {
                        string neadName = need[j].Name.ToString();

                        string rowAtrb = Convert.ToString(need[j].FirstAttribute);
                        if (rowAtrb.Contains("ss:Index"))
                        {
                            string getStr =  GetValue(Convert.ToString(need[j].FirstAttribute), "\"", "\"");
                            if (getStr != "" && getStr != null)
                            {
                                for (int n = value; n < Convert.ToInt32(getStr) - 1; n++){
                                    value++;
                                    rowList.Add("");
                                }
                            }
                        }
                        value++;
                        neadList.Add(need[j].Value);
                         确定是表格内容(Sheet)
                        //if (name.Contains("Worksheet"))
                        //    neadList.Add(need[j].Value);
                    }

                    if (debug)
                    {
                        Console.WriteLine("读取到需要的一行了");  
                        for (int j = 0; j < need.Count; j++)
                        {
                            Console.WriteLine("读取到的一行参数如下:");
                            Console.WriteLine(need[j].Value);
                        }
                    }
                }
            }
        }
        if (!haveNeedTable) // 没有对应表格
            return 1;

        return 0;      // 返回0则表示正常读取到参数
    }
    // 从str中读取start开始到end结束的string并返回
    public string GetValue(string str, string start, string end)
    {
        Regex rg = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
        return rg.Match(str).Value;
    }
    // 读取表格中所有数据已表格返回
    public int ReadExcelAll(List<List<string>> neadList, string fileName, string sheetName)
    {
        XElement element = null;
        bool haveNeedTable = false;
        try
        {
            element = XElement.Load(@fileName);
        }
        catch
        {
            MessageBox.Show("加载文件失败");
            return 3;
        }
        List<XElement> sheet = element.Elements().ToList();
        for (int i = 0; i < sheet.Count; i++)
        {

            string name = sheet[i].Name.ToString();
            // 确定是表格内容(Sheet)
            if (name.Contains("Worksheet"))
            {
                string str = GetValue(sheet[i].FirstAttribute.ToString(), "\"", "\"");
                // 有需要的Sheet
                if (sheetName == str)
                {
                    haveNeedTable = true;
                    List<XElement> listInSheet = sheet[i].Elements().ToList();
                    List<XElement> Rows = listInSheet[0].Elements().ToList();
                    for (int m = 0; m < Rows.Count; m++)
                    {
                        string row = Rows[m].Name.ToString();
                        if (debug)
                            Console.WriteLine("确定这行是什么:" + row);
                        // 确定是表格内容(Sheet),把不是的移出后再处理
                        if (!row.Contains("Row"))
                        {
                            Rows.RemoveAt(m);
                            m--;
                        }
                    }

                    for(int j = 0; j < Rows.Count; j++)
                    {
                        List<string> rowList = new List<string>();
                        List<XElement> row = Rows[j].Elements().ToList();
                        int value = 0;
                        for(int m = 0; m < row.Count; m++)
                        {
                            // Contains是否包含
                            string rowAtrb = Convert.ToString(row[m].FirstAttribute);
                            if (rowAtrb.Contains("ss:Index"))
                            {
                                string getStr = GetValue(Convert.ToString(row[m].FirstAttribute), "\"", "\"");
                                if (getStr != "" && getStr != null)
                                {
                                    for (int n = value; n < Convert.ToInt32(getStr) - 1; n++)
                                    {
                                        value++;
                                        rowList.Add("");
                                    }
                                }
                            }
                            value++;
                            rowList.Add(row[m].Value);
                            if (debug)
                                Console.WriteLine("添加" + j + "的一个变量为: " + row[m].Value);
                        }
                        neadList.Add(rowList);
                    }
                }
            }
        }
        if (!haveNeedTable) // 没有对应表格
            return 1;
        return 0;
    }
}

5、实际上,上面我用呢,是这样加的:

        public List<List<string>> SheetList = new List<List<string>>();
        public MyXML(string fileName, string sheetName)
        {
            if (0 != ReadExcelAll(SheetList, fileName, sheetName))
                MessageBox.Show("表格加载失败");
        }
        // 读取一行
        public int ReadExcelRow(List<string> needList, int needRow)
        {
            needRow--;
            if (SheetList == null)
                return 1;

            if (needRow > SheetList.Count)
                return 2;

            for(int i = 0; i < SheetList[needRow].Count; i++)
            {
                needList.Add(SheetList[needRow][i]);
            }

            return 0;
        }

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值