【发布时间】:2020-05-04 21:51:50
【问题描述】:
我有一个要求,我需要将导入到“datagridview”的excel文件中的数据导出为指定格式“xml”,首先我从excel填充到datagrid并保存为Xml,遵循这段代码
namespace SAMPLE_
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
这里我是使用 Microsoft Office Interop Excel 导入 Excel 文件:
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Microsoft.Office.Interop.Excel.Application xlApp;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorlSheet;
Microsoft.Office.Interop.Excel.Range xlRange;
int xlRow;
string strfileName;
openFilalog1.Filter = "Excel Office | *.xls; *.xlsx";
openFilalog1.ShowDialog();
strfileName = openFilalog1.FileName;
if(strfileName != string.Empty)
{
xlApp = new Microsoft.Office.Interop.Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(strfileName);
xlWorlSheet = xlWorkBook.Worksheets["SHEET1"];
xlRange = xlWorlSheet.UsedRange;
int i=0;
for (xlRow = 2; xlRow <= xlRange.Rows.Count; xlRow++)
{
if(xlRange.Cells[xlRow,2].Text != "")
{
i++;
dataGridView1.Rows.Add(i, xlRange.Cells[xlRow, 1].Text, xlRange.Cells[xlRow,
2].Text,
xlRange.Cells[xlRow, 3].Text, xlRange.Cells[xlRow, 4].Text,
xlRange.Cells[xlRow, 5].Text, xlRange.Cells[xlRow, 6].Text,
xlRange.Cells[xlRow, 7].Text, xlRange.Cells[xlRow, 8].Text,
xlRange.Cells[xlRow, 9].Text,xlRange.Cells[xlRow, 10].Text,
xlRange.Cells[xlRow, 11].Text,xlRange.Cells[xlRow, 12].Text,
xlRange.Cells[xlRow, 13].Text);
}
}
xlWorkBook.Close();
xlApp.Quit();
}
这是我用来导出的按钮:
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = (DataSet)dataGridView1.DataSource;
SaveFilalog sfd = new SaveFilalog();
sfd.Filter = "SHEET1|*.xml";
if (sfd.ShowDialog() == DialogResult.OK)
{
try
{
ds.Tables[0].WriteXml(sfd.FileName);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}
【问题讨论】:
-
我需要知道xml格式。显然当前写入 ds.Tables[0].WriteXml(sfd.FileName);格式不正确。
-
那么正确的格式是什么?
-
你必须告诉我。您说“以指定格式'xml”。那么格式是什么?
-
这是我想要的输出 xml 格式:
<rd> <id>column 1 cell 1</id> <name>column 2 cell 1</name> <last>column 3 cell 1</last> <phone>column 4 cell 1</phone> <refF> <adresse>column 5 cell 1</adresse> <citie>column 6 cell 1</citie> </refF> <age>column 7 cell 1</age> <mp> <degree>column 8 cell 1</degree> </mp> <dpa>column 9 cell 1</dpa> </rd>