using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using System.Xml;
namespace EXCELTOXML
{
public partial class Form1 : Form
{
List<student> li = new List<student>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
int rw = 0;
int cl = 1;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(@"C:\images\docs\abc.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
range = xlWorkSheet.UsedRange;
rw = range.Rows.Count;
//
//data read code...............................................
for (int i = 2; i <= rw; i++)
{
student s = new student();
s.id = (int)(range.Cells[i, 1] as Excel.Range).Value;
s.Name = (string)(range.Cells[i, 2] as Excel.Range).Value;
s.Marks = (int)(range.Cells[i, 3] as Excel.Range).Value;
li.Add(s);
}
//data read code...............................................
//
xlWorkBook.Close(true, null, null);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
dataGridView1.DataSource = li;
}
private void button2_Click(object sender, EventArgs e)
{
XmlTextWriter writer = new XmlTextWriter(@"C:\images\docs\salman.xml", System.Text.Encoding.UTF8);
writer.WriteStartDocument(true);
writer.Formatting = Formatting.Indented;
writer.Indentation = 2;
writer.WriteStartElement("Students");
foreach (var item in li)
{
createnode(item, writer);
}
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
MessageBox.Show("XML File created ! ");
}
private void createnode(student s, XmlTextWriter writer)
{
writer.WriteStartElement("Student");
//id...............................
writer.WriteStartElement("id");
writer.WriteString(s.id.ToString());
writer.WriteEndElement();
//................name
writer.WriteStartElement("Name");
writer.WriteString(s.Name.ToString());
writer.WriteEndElement();
//................name
writer.WriteStartElement("Marks");
writer.WriteString(s.Marks.ToString());
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}
No comments:
Post a Comment