【发布时间】:2018-12-23 18:32:39
【问题描述】:
我编写了一个快速代码来尝试从 XML 文件中获取元素并将它们放入一个 excel 表中,但我没有从我的节点中得到任何东西。我不明白为什么。
我一直在尝试使用 XMLDocument 的 Microsoft 文档从节点获取所需内容的不同方法,但结果始终相同,它打印的是空行。
[STAThread]
static void Main(string[] args)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
XmlDocument xmlDocument = new XmlDocument();
System.Data.DataTable table = new System.Data.DataTable();
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook workBook;
Microsoft.Office.Interop.Excel.Worksheet workSheet;
int rowCount = 1;
openFileDialog.Filter = "XML Files|*.xml";
openFileDialog.Title = "Select the SMS backup";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
xmlDocument.PreserveWhitespace = true;
try
{
xmlDocument.Load(openFileDialog.FileName);
}
catch (System.IO.FileNotFoundException)
{
}
table.Columns.Add("Contact name", typeof(string));
table.Columns.Add("Date", typeof(DataFormats));
table.Columns.Add("Message", typeof(string));
foreach (XmlNode node in xmlDocument.DocumentElement.ChildNodes)
{
System.Diagnostics.Debug.WriteLine(node.InnerText);
if (node.InnerText.Contains("contact_name"))
{
table.Rows.Add(
node.Attributes["contact_name"]?.InnerText,
node.Attributes["readable_date"]?.InnerText,
node.Attributes["body"]?.InnerText
);
}
}
try
{
excel = new Microsoft.Office.Interop.Excel.Application
{
Visible = true,
DisplayAlerts = false
};
workBook = excel.Workbooks.Add(Type.Missing);
workSheet = (Microsoft.Office.Interop.Excel.Worksheet) workBook.ActiveSheet;
workSheet.Name = "SMS backup";
foreach (System.Data.DataRow dataRow in table.Rows)
{
rowCount += 1;
for (int i = 1; i <= table.Columns.Count; i++)
{
workSheet.Cells[rowCount, i] = dataRow[i - 1].ToString();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
workSheet = null;
workBook = null;
}
}
}
【问题讨论】:
-
使用EPplus,将你的xml文件读入数据表,输出到excel。大约需要 10 行代码
标签: c# xml-parsing