C#中xml数据转化dataset和dataset转到excel中

本文介绍了一个将XML文件转换为DataSet的方法,并提供了一种将DataSet中的数据导出到Excel的工作流程。该方法首先加载XML文件并将其转换为XmlDocument对象,然后通过XmlTextReader读取并填充DataSet。此外,还实现了一个将DataSet中的数据写入Excel的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



public static DataSet ds = new DataSet();
        //convert the xml file to dataset
        public DataSet xmlToDataset(string xmlFullPath) {
            XmlDocument xmldoc = null;
            XmlTextReader reader=null;
            StringReader stream=null;
            try
            {
                xmldoc = new XmlDocument();
                xmldoc.Load(xmlFullPath);
                stream = new StringReader(xmldoc.InnerXml);
                //load the stream to xmltextreader
                reader = new XmlTextReader(stream);
                ds.ReadXml(reader);
                 return ds;
            }catch(Exception e){
                throw new Exception("Load the xml file fail."+e.Message);
           
            }      
             
        }
        //convert the dataset to excel
        public bool DataSetToExcel(DataSet ds) {
            bool isSuccess = false;
            if(ds==null){
                return isSuccess;
            }          
           //create excel
            Application excel = new Application();
            excel.Workbooks.Add(true);
            excel.Visible = true;

            int rowNum = ds.Tables[0].Rows.Count;
            int colNum = ds.Tables[0].Columns.Count;
           //get the column name
            for(int i=0;i<colNum;i++){
                excel.Cells[1, i+1] = ds.Tables[0].Columns[i].ColumnName;
           
            }
            //write the data
            for (int i = 0; i < rowNum;i++ ) {
                for (int j = 0; j < colNum;j++ ) {
                    excel.Cells[i + 2, j + 1] = ds.Tables[0].Rows[i][j].ToString();
               
                }
                      
            }
            isSuccess = true;
            return isSuccess;
       
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值