



时间:2022-03-14 关注公众号 来源:搜狗指南
C# 将XML转为excel(附代码) C# 将XML转为word。以下内容通过C#及代码展示如何将XML文件转换为Excel文件,可转为.xls以及.xlsx。
工具/材料
测试文件:XML文件
Excel类库:spire.xls.dll 11.3.4程序集文件
目标文档:Excel (.xls及.xlsx格式)
操作方法
01
准备xml源文档,将文件存入VS项目文件夹Debug路径下。这里的文件路径也可以自定义为其他路径。(本次测试代码中的文件路径为项目文件夹路径:C:\Users\Administrator\Documents\Visual Studio 2013\Projects\Conversion_XLS\XmlToExcel\bin\Debug。),xml文件在vs程序中的打开效果如下:
02
在程序中引入如下必要程序集文件:
03
在程序中键入如下代码:
【C#】
using Spire.Xls;
namespace XmlToExcel
{
class Program
{
static void Main(string[] args)
{
//加载XML文件
Workbook wb = new Workbook();
wb.LoadFromXml("test.xml");
//保存为.xls格式
wb.SaveToFile("ToExcel.xls");
//保存为.xlsx格式
wb.SaveToFile("ToExcel.xlsx");
}
}
}
【】
Imports Spire.Xls
Namespace XmlToExcel
Class Program
Private Shared Sub Main(args As String())
'加载XML文件
Dim wb As New Workbook()
wb.LoadFromXml("test.xml")
'保存为.xls格式
wb.SaveToFile("ToExcel.xls")
'保存为.xlsx格式
wb.SaveToFile("ToExcel.xlsx")
End Sub
End Class
End Namespace
04
运行程序,生成结果文档。可在项目文件夹路径下查看生成的Excel文档,如下图:
程序中所需必要程序集如下图:
★ 程序集获取:官方地址;Nuget地址
用于测试的XML文件如下,在IE中的打开效果:
本次代码环境中的文件路径为VS项目程序文件夹路径,文件路径另自定义。
【C#】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
usingSpire.Doc;
namespaceXMLtoWord
{
classProgram
{
staticvoidMain(string[]
args)
{
//加载xml文档
Document
doc =newDocument();
doc.LoadFromFile("test.xml",FileFormat.Xml);
//保存为.docx格式
doc.SaveToFile("ToWord.docx",
FileFormat.Docx2013);
System.Diagnostics.Process.Start("ToWord.docx");
//保存为.doc格式
doc.SaveToFile("ToWord.doc",FileFormat.Doc);
System.Diagnostics.Process.Start("ToWord.doc");
}
}
}
|
转换结果:
【】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
ImportsSpire.Doc
NamespaceXMLtoWord
ClassProgram
PrivateSharedSubMain(argsAsString())
'加载xml文档
DimdocAsNewDocument()
doc.LoadFromFile("test.xml",
FileFormat.Xml)
'保存为.docx格式
doc.SaveToFile("ToWord.docx",
FileFormat.Docx2013)
System.Diagnostics.Process.Start("ToWord.docx")
'保存为.doc格式
doc.SaveToFile("ToWord.doc",
FileFormat.Doc)
System.Diagnostics.Process.Start("ToWord.doc")
EndSub
EndClass
EndNamespace
|
文章内容来源于网络,不代表本站立场,若侵犯到您的权益,可联系我们删除。(本站为非盈利性质网站)
电话:13918309914
QQ:1967830372
邮箱:rjfawu@163.com