gpt4 book ai didi

c# - 如何以编程方式将 xml 转换为 excel 文件

转载 作者:数据小太阳 更新时间:2023-10-29 02:18:18 27 4
gpt4 key购买 nike

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

我如何以编程方式执行此操作?

最佳答案

可以使用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;

如图所示创建 excel 应用程序:

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 文件中的所有项目

// 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 对象。

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

关于c# - 如何以编程方式将 xml 转换为 excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2494967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com