using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using System.Xml.Schema; namespace myXMLReader { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { treeResult.Nodes.Clear(); readXml(); } private void readXml() { // todo String sourcePath = "f:/test.xml"; System.Xml.XmlDocument sourceXml = new XmlDocument(); try { sourceXml.Load(sourcePath); } catch (XmlException e) { StringBuilder sb = addRootToXml(sourcePath); sourceXml.LoadXml(sb.ToString()); } catch (Exception e) { return; } foreach (XmlNode rootNode in sourceXml.ChildNodes) { if (rootNode.NodeType == XmlNodeType.Element) { TreeNode tNode = new TreeNode(rootNode.Name); readChildNode(rootNode, tNode); treeResult.Nodes.Add(tNode); } } creatToExcel(); } private void readChildNode(XmlNode node, TreeNode tNode) { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.NodeType != XmlNodeType.Element) { continue; } TreeNode tChildNode = new TreeNode(childNode.Name); tNode.Nodes.Add(tChildNode); if (childNode.HasChildNodes) { readChildNode(childNode, tChildNode); } } } private StringBuilder addRootToXml(string path) { TextReader reader = File.OpenText(path); StringBuilder sb = new StringBuilder(reader.ReadToEnd()); sb.Insert(0, "<XML>"); sb.Append("</XML>"); return sb; } private int writeRowIndex = 1; private void creatToExcel() { int startColumn = 1; HSSFWorkbook hssfworkbook = new HSSFWorkbook(); 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 = new FileStream(@"f:/test.xls", FileMode.Create); hssfworkbook.Write(file); file.Close(); } private void writeNodeToExcel(ISheet sheet, TreeNode node, int columnIndex) { IRow row = sheet.CreateRow(getRow()); ICell cell = row.CreateCell(columnIndex); cell.SetCellValue(node.Text); for (int i = 0; i < node.Nodes.Count; i++) { writeNodeToExcel(sheet, node.Nodes[i], columnIndex + 1); } } private int getRow() { return writeRowIndex++; } } }
最近需要一个读取xml,将节点写入Excel的功能,还没有完善,暂时记录一下。
时间: 2024-10-09 20:43:43