usingNpoi. HPSF;usingNpoi. HSSF. Usermodel;usingNpoi. Ss. Usermodel;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;usingSystem.Xml;usingSystem.Xml.Schema;namespacemyxmlreader{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Private voidButton1_Click (Objectsender, EventArgs e) {treeResult.Nodes.Clear (); READXML (); } Private voidreadXml () {//TodoString SourcePath ="F:/test.xml"; System.Xml.XmlDocument SourceXML=NewXmlDocument (); Try{sourcexml.load (sourcepath); } Catch(XmlException e) {StringBuilder sb=Addroottoxml (SourcePath); Sourcexml.loadxml (sb.) ToString ()); } Catch(Exception e) {return; } foreach(XmlNode RootNodeinchsourcexml.childnodes) {if(Rootnode.nodetype = =xmlnodetype.element) {TreeNode tnode=NewTreeNode (rootnode.name); Readchildnode (RootNode, tnode); TREERESULT.NODES.ADD (tnode); }} creattoexcel (); } Private voidReadchildnode (XmlNode node, TreeNode tnode) {foreach(XmlNode Childnodeinchnode. ChildNodes) {if(Childnode.nodetype! =xmlnodetype.element) {Continue; } TreeNode Tchildnode=NewTreeNode (childnode.name); TNODE.NODES.ADD (Tchildnode); if(childnode.haschildnodes) {Readchildnode (Childnode, Tchildnode); } } } PrivateStringBuilder Addroottoxml (stringpath) {TextReader Reader=file.opentext (path); StringBuilder SB=NewStringBuilder (reader. ReadToEnd ()); Sb. Insert (0,"<XML>"); Sb. Append ("</XML>"); returnSB; } Private intWriterowindex =1; Private voidCreattoexcel () {intStartColumn =1; Hssfworkbook Hssfworkbook=NewHssfworkbook (); Documentsummaryinformation DSi=propertysetfactory.createdocumentsummaryinformation (); Dsi.company="Npoi Team"; Hssfworkbook. Documentsummaryinformation=DSi; SummaryInformation si=propertysetfactory.createsummaryinformation (); Si. Subject="Npoi SDK Example"; Hssfworkbook. SummaryInformation=si; Isheet sheet= Hssfworkbook. Createsheet ("Sheet1"); Writenodetoexcel (sheet, treeresult.nodes[0], startcolumn); FileStream file=NewFileStream (@"F:/test.xls", FileMode.Create); Hssfworkbook. Write (file); File. Close (); } Private voidWritenodetoexcel (isheet Sheet, TreeNode node,intcolumnindex) {IRow row=sheet. CreateRow (GetRow ()); Icell Cell=row. Createcell (columnindex); Cell. Setcellvalue (node. Text); for(inti =0; I < node. Nodes.count; i++) {writenodetoexcel (Sheet, node. Nodes[i], ColumnIndex+1); } } Private intGetRow () {returnwriterowindex++; } }}
Recently need a read XML, the node write to Excel function, not perfect, temporarily recorded.
Read the XML and save the node to excal