如何以编程方式将xml转换为excel文件 [英] How to convert xml to excel file programmatically

查看:67
本文介绍了如何以编程方式将xml转换为excel文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文档,其中包含我的项目的少量数据,我想将xml转换为excel文件(Microsoft Office Excel 2003及更高版本)

I have a xml document holding a small data for my project where I want to convert my xml to an excel file (microsoft office excel 2003 and over)

我该如何以编程方式做到这一点?

How can I do this programmatically?

推荐答案

可以通过使用 Microsoft.Office.Interop.Excel 来实现,如下所示:

It can be achieved by using Microsoft.Office.Interop.Excel as shown below:

首先声明这些必要的引用.

First of all declare these necessary references.

using System;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using System.Diagnostics;
using Microsoft.Win32;

比如下所示创建excel应用程序

Than create excel app as shown:

Excel.Application excel2; // Create Excel app
Excel.Workbook DataSource; // Create Workbook
Excel.Worksheet DataSheet; // Create Worksheet
excel2 = new Excel.Application(); // Start an Excel app
DataSource = (Excel.Workbook)excel2.Workbooks.Add(1); // Add a Workbook inside
string tempFolder = System.IO.Path.GetTempPath(); // Get folder 
string FileName = openFileDialog1.FileName.ToString(); // Get xml file name

之后,在循环中使用以下代码来确保xml文件中的所有项目均已复制

After that use below code in a loop to ensure all items in xml file are copied

// Open that xml file with excel
DataSource = excel2.Workbooks.Open(FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
// Get items from xml file
DataSheet = DataSource.Worksheets.get_Item(1);
// Create another Excel app as object
Object xl_app;
xl_app = GetObj(1, "Excel.Application");
Excel.Application xlApp = (Excel.Application)xl_app;
// Set previous Excel app (Xml) as ReportPage
Excel.Application ReportPage = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// Copy items from ReportPage(Xml) to current Excel object
Excel.Workbook Copy_To_Excel = ReportPage.ActiveWorkbook;

现在,我们有一个名为Copy_To_Excel的Excel对象,其中包含Xml中的所有项目.我们可以使用所需的名称保存并关闭Excel对象.

Now we have an Excel object named as Copy_To_Excel that contains all items in Xml.. We can save and close the Excel object with the name we want..

Copy_To_Excel.Save("thePath\theFileName");
Copy_To_Excel.Close();

这篇关于如何以编程方式将xml转换为excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆