闲来无事,做了一点C#调用XML以及Excel的操作。
参考:
至于Excel部分的,那个大神帅的发光使我的脑底片过于曝光导致记忆模糊,等等不可抗拒的原因,总的来说,就是我忘了,果咩果咩。
废话说完,进入正题:
一、从Excel中读取数据,并传入写入XML.
XML SetXML = new XML();//实例化XML,因为我定义的函数是void,如果是static就不用实例化了
private void button1_Click(object sender, EventArgs e)
{
string readFilePathName = @"C:待读取.xls";//待读取的excel文档
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + readFilePathName + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";//文档格式转换
OleDbConnection conn = new OleDbConnection(strConn);//数据源
conn.Open();
System.Data.DataTable dt = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);//数据获取
DataSet ds = new DataSet();//缓存
string tableName = dt.Rows[0][2].ToString().Trim();//获取Excel的表名,默认值是sheet1 表名
string strSql = "select * from [" + tableName + "]";
OleDbCommand cmd = new OleDbCommand(strSql, conn);//用于sql处理
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);//用于填充Dataset和更新数据源
da.Fill(ds);//填充数据
SetXML.GenerateXMLFile_A(ds);
//获得该节点的子节点(即:该节点的第一层子节点)
XmlNodeList firstLevelNodeList = SetXML.GetXMLInformation_w();
foreach (XmlNode node in firstLevelNodeList)
{
//获得该节点的属性集合
XmlAttributeCollection attributeCol = node.Attributes;
foreach (XmlAttribute attri in attributeCol)
{
//获得属性名称与属性值
string name = attri.Name;
string value = attri.Value;
}
//判断此节点是否还有子节点
if (node.HasChildNodes)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
//获取该节点的第一个子节点
XmlNode secondLevelNode1 = node.ChildNodes[i];
//获取该节点的名字
string name = secondLevelNode1.Name;
//获取该节点的值(即:InnerText)
string innerText = secondLevelNode1.InnerText;
}
}
}
addListView(firstLevelNodeList);//存入listview中
}
private void addListView(XmlNodeList firstLevelNodeList)
{
int y = 1;
foreach (XmlNode node in firstLevelNodeList)
{
string[] CLSs = new string[6];
//获得该节点的属性集合
XmlAttributeCollection attributeCol = node.Attributes;
foreach (XmlAttribute attri in attributeCol)
{
//获得属性名称与属性值
string name = attri.Name;
string value = attri.Value;
//Console.WriteLine("{0} = {1}", name, value);
if (y == 1)
{
listView1.Columns.Add(attri.Name, 60, HorizontalAlignment.Left);
CLSs[0] = attri.Value;
}
else
{
CLSs[0] = attri.Value;
}
}
//判断此节点是否还有子节点
if (node.HasChildNodes)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
//获取该节点的第一个子节点
XmlNode secondLevelNode1 = node.ChildNodes[i];
//获取该节点的名字
string name = secondLevelNode1.Name;
//获取该节点的值(即:InnerText)
string innerText = secondLevelNode1.InnerText;
if (y == 1)
{
listView1.Columns.Add(name, 60, HorizontalAlignment.Left);
CLSs[i+1] = innerText;
}
else
{
CLSs[i + 1] = innerText;
}
//Console.WriteLine("{0} = {1}", name, innerText);
}
}
y++;
ListViewItem liv = new ListViewItem(CLSs);
liv.ImageIndex = 1;
listView1.Items.Add(liv);
}
}
所用到的XML类
namespace Addexcel
{
class XML
{
public void GenerateXMLFile_A(DataSet ds)//生成xml文件
{
try
{
//初始化一个xml实例
XmlDocument myXmlDoc = new XmlDocument();
//创建Xml的根节点
XmlElement rootElement = myXmlDoc.CreateElement("数据");
//将根节点加入到xml文件中(AppendChild)
myXmlDoc.AppendChild(rootElement);
//将xml文件保存到制定的路径下
myXmlDoc.Save("mypay.xml");
foreach (DataRow col in ds.Tables[0].Rows)//行
{
int i = 0;
XmlElement firstLevelElement2 = myXmlDoc.CreateElement(col[i].ToString());
foreach (DataColumn dcA in ds.Tables[0].Columns)//判断列数
{
if (i == 0)
{
firstLevelElement2 = myXmlDoc.CreateElement(dcA.ToString());
firstLevelElement2.SetAttribute(dcA.ToString(), col[i].ToString());
myXmlDoc.LastChild.AppendChild(firstLevelElement2);
}
else
{
XmlElement secondLevelElement21 = myXmlDoc.CreateElement(dcA.ToString());
secondLevelElement21.InnerText = col[i].ToString();
firstLevelElement2.AppendChild(secondLevelElement21);
}
i++;
}
}
//将xml文件保存到制定的路径下
myXmlDoc.Save("mypay.xml");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public XmlNodeList GetXMLInformation_w()//遍历xml文件的信息
{
try
{
//初始化一个xml实例
XmlDocument myXmlDoc = new XmlDocument();
//加载XML文件(参数为xml文件的路径)
myXmlDoc.Load("mypay.xml");
//获得第一个姓名匹配的节点(SelectSingNode):此xml文件的根节点
XmlNode rootNode = myXmlDoc.SelectSingleNode("数据");
//分别获得该节点的InnerXml和OuterXml信息
string innerXmlInfo = rootNode.InnerXml.ToString();
string outerXmlInfo = rootNode.OuterXml.ToString();
//获得该节点的子节点(即:该节点的第一层子节点)
XmlNodeList firstLevelNodeList = rootNode.ChildNodes;
return firstLevelNodeList;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
}
Excel导出部分
private int LetterToInt(string str)
{
byte[] array = new byte[1]; //定义一组数组array
array = System.Text.Encoding.ASCII.GetBytes(str); //string转换的字母
int asciicode = (short)(array[0]);
return asciicode;
}
private string IntToLetter(int t)
{
byte[] array = new byte[1];
array[0] = (byte)t;//ASCII码强制转换二进制
string ty = Convert.ToString(System.Text.Encoding.ASCII.GetString(array));
return ty;
}
private void button2_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application xapp = new Microsoft.Office.Interop.Excel.Application();
string filePathName = @"C:test.xlsx";
Microsoft.Office.Interop.Excel._Workbook xbook=xapp.Workbooks.Open(filePathName,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value, Missing.Value,Missing.Value,Missing.Value);
Microsoft.Office.Interop.Excel.Worksheet xsheet = xbook.Sheets[1];
//获得该节点的子节点(即:该节点的第一层子节点)
XmlNodeList firstLevelNodeList = SetXML.GetXMLInformation_w();
int x = 0; int y = 0;
string line = "1";
string list = "A";
y = Convert.ToInt32(line);
x = LetterToInt(list);
foreach (XmlNode node in firstLevelNodeList)
{
//获得该节点的属性集合
XmlAttributeCollection attributeCol = node.Attributes;
foreach (XmlAttribute attri in attributeCol)
{
//获得属性名称与属性值
string name = attri.Name;
string value = attri.Value;
//Console.WriteLine("{0} = {1}", name, value);
if (y == 1)
{
Microsoft.Office.Interop.Excel.Range lie = xsheet.get_Range(list + line, Missing.Value);
lie.Value2 = attri.Name;
int y1 = y + 1;
string yt = y1.ToString();
Microsoft.Office.Interop.Excel.Range lie1 = xsheet.get_Range(list + yt, Missing.Value);
lie1.Value2 = attri.Value;
}
else
{
Microsoft.Office.Interop.Excel.Range lie = xsheet.get_Range(list + line, Missing.Value);
lie.Value2 = attri.Value;
}
x++;
list = IntToLetter(x);
//Console.WriteLine(list);
}
//判断此节点是否还有子节点
if (node.HasChildNodes)
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
//获取该节点的第一个子节点
XmlNode secondLevelNode1 = node.ChildNodes[i];
//获取该节点的名字
string name = secondLevelNode1.Name;
//获取该节点的值(即:InnerText)
string innerText = secondLevelNode1.InnerText;
if (y == 1)
{
Microsoft.Office.Interop.Excel.Range lie = xsheet.get_Range(list + line, Missing.Value);
lie.Value2 = name;
Microsoft.Office.Interop.Excel.Range lie1 = xsheet.get_Range(list + (y+1).ToString(), Missing.Value);
lie1.Value2 = innerText;
}
else
{
Microsoft.Office.Interop.Excel.Range lie = xsheet.get_Range(list + line, Missing.Value);
lie.Value2 = innerText;
}
x++;
list = IntToLetter(x);
//Console.WriteLine("{0} = {1}", name, innerText);
}
list = "A";
x = LetterToInt(list);
}
if (y != 1)
y++;
else
y += 2;
line = y.ToString();
}
xbook.Save();
xbook.Close();
//xbook.SaveAs(@"C:\test.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
// Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
MessageBox.Show("写入成功");
}
致此,代码贴完了,上效果
按下读取数据
虽然内容非常中二,容易引起不适,但是胜在影响不大,还能接受
xml:
吐槽同上
原来的Excel
导出的Excel跟上面的图片相同
至于还有其他的创建文件啊,文件保存到某目录下啊,就懒得去做了。
完!