我有一个xml文档,为我的项目保存一个小数据,我想将我的xml转换为excel文件(microsoft office excel 2003及以上版本)
我该如何以编程方式执行此操作?
小智 8
它可以通过使用Microsoft.Office.Interop.Excel如下所示实现:
首先声明这些必要的参考.
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;
Run Code Online (Sandbox Code Playgroud)
比如图所示创建excel app:
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
Run Code Online (Sandbox Code Playgroud)
之后在循环中使用下面的代码来确保复制xml文件中的所有项目
// 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;
Run Code Online (Sandbox Code Playgroud)
现在我们有一个名为Copy_To_Excel的Excel对象,其中包含Xml中的所有项目.我们可以使用我们想要的名称保存和关闭Excel对象.
Copy_To_Excel.Save("thePath\theFileName");
Copy_To_Excel.Close();
Run Code Online (Sandbox Code Playgroud)