现在的位置: 首页 > 综合 > 正文

ExcelToXml小工具

2017年10月25日 ⁄ 综合 ⁄ 共 5413字 ⁄ 字号 评论关闭

很久没有写cs端的,鉴于客户需求,要将excel转换成xml文件的一个小工具。

界面效果:

一开始认为winform中有类似web中的上传控件,可能还是不熟悉,所有用了一个openFileDialog。

分为几个部分: 

#region 将Excel导成xml文件
        private void button1_Click(object sender, EventArgs e)
        {
            if (!ExistsNetFramework())
            {
                MessageBox.Show("需要安装net framework4.0版本");
                return;
            }
            if (textBox1.Text != "")
            {               
                int version = ExistsRegedit();
                string strConn = "";
                string path = textBox1.Text.Substring(textBox1.Text.Length - 4);

                if (path == "xlsx")
                {
                    if (version == 1)
                    {
                        MessageBox.Show("Excel版本不匹配!");
                        return;
                    }
                    else if (version == 2 || version == 3)
                    {
                        //2007格式
                        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                    }
                    else
                    {
                        MessageBox.Show("没有安装Excel文件,或者找不到对应版本的文件!");
                        return;
                    }
                }
                else if (path == ".xls")
                {
                    if (version == 1)
                    {
                        //2003格式
                        strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + textBox1.Text + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                    }
                    else if (version == 2 || version == 3)
                    {
                        //2007格式
                        strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
                    }
                    else
                    {
                        MessageBox.Show("没有安装Excel文件,或者找不到对应版本的文件!");
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("文件格式不正确");
                    return;
                }
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                String sql = "SELECT * FROM  [Sheet1$]";
                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
                DataSet dsExcle = new DataSet();
                OleDaExcel.Fill(dsExcle, "Product");

                DataSet dsEncodeExcel = new DataSet();
                foreach (DataTable dt in dsExcle.Tables)
                {
                    DataTable dtEncodeExcel = new DataTable();
                    if (dt.Rows.Count > 0)
                    {
                        int count = dt.Rows.Count;
                        //获取表结构
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            for (int j = 0; j < dt.Columns.Count; j++)
                            {
                                if (i == 0)
                                    dtEncodeExcel.Columns.Add(dt.Columns[j].ColumnName, typeof(System.String));
                            }
                            DataRow drEncodeExcel = dtEncodeExcel.NewRow();
                            //dtEncodeExcel.ImportRow(dt.Rows[i]);
                            dtEncodeExcel.ImportRow(GetEncodeDR(dt.Rows[i], drEncodeExcel));
                            dtEncodeExcel.Rows.Add(drEncodeExcel);
                        }
                    }
                    else
                    {
                        MessageBox.Show("表中没有数据");
                        return;
                    }
                    dsEncodeExcel.Tables.Add(dtEncodeExcel);
                }
                ExcelToXml(dsEncodeExcel);
                OleConn.Close();
            }
            else
            {
                MessageBox.Show("请先导入Excel!");
            }
        }
        #endregion

 

  private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {          
            string appPath = ((OpenFileDialog)sender).FileName;
            try
            {
                textBox1.Text = appPath;
                //带参数启动应用程序
                //System.Diagnostics.ProcessStartInfo   startInfo   =   new   System.Diagnostics.ProcessStartInfo(   ); 
                //startInfo.FileName   =   "执行EXE的文件名 "; 
                //startInfo.Arguments   =   "参数数组 "; 
                //System.Diagnostics.Process.Start(   startInfo   );
                //do something 。。。
                //Process.Start(appPath);
            }
            catch (Exception)
            {
                MessageBox.Show("启动失败!");
            }
        }

        #region 获取文件路径
        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = @"打开(Open)";
            openFileDialog.Filter = @"EXCEl文件(*.xlsx)|*.xlsx|EXCEl文件(*.xls)|*.xls";
            openFileDialog.ValidateNames = true;     //文件有效性验证ValidateNames,验证用户输入是否是一个有效的Windows文件名
              openFileDialog.CheckFileExists = true;  //验证路径有效性
              openFileDialog.CheckPathExists = true; //验证文件有效性
              openFileDialog.FileOk += new CancelEventHandler(openFileDialog_FileOk);
            openFileDialog.ShowDialog();
        }
        #endregion

        #region 将excel文件写成xml
        private void ExcelToXml(DataSet dtExcel)
        {
            DataSet ds = new DataSet();
            //string filename = "C:\\Users\\Administrator\\Desktop\\Product.xml ";
            dtExcel.WriteXml("Product.xml");
            MessageBox.Show("导出xml文件成功!");
            //MessageBox.Show("桌面上生成导出xml文件成功!");
        }
        #endregion
 #region excel数据加密
        private string Encode(string filed)
        {	   //每个人的加密方法各不相同。
        }
        #endregion 
#region  将dr内容进行加密处理
        private DataRow GetEncodeDR(DataRow dr, DataRow drencode)
        {
            for (int i = 0; i < dr.ItemArray.Length; i++)
            {
                if (dr[i].ToString() == "" || dr[i].ToString() == string.Empty)
                    dr[i] = DBNull.Value;
                else
                    if (dr[i].ToString().Contains(""))
                        dr[i].ToString().Replace(" ", "");
                drencode[i] = Encode(dr[i].ToString());
            }
            return drencode;
        }
        #endregion 

 #region 判断本机excel安装的是office2003,还是office2007以上版本,还是office2010版本         public int ExistsRegedit()         {             int num = 0;             RegistryKey rk = Registry.LocalMachine;             RegistryKey akey2003 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\11.0\\Excel\\InstallRoot\\");             RegistryKey akey2007 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\12.0\\Excel\\InstallRoot\\");             RegistryKey akey2010 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\Office\\14.0\\Excel\\InstallRoot\\");

            //检查本机是否安装Office2010             if (akey2010 != null)                 return num = 3;

            //检查本机是否安装Office2007             if (akey2007 != null)                 return num = 2;

            //检查本机是否安装Office2003             if (akey2003 != null)                 return num = 1;

            return num;         }         #endregion

        #region 通过注册表判读是否安装.net framework 4.0版本         public bool ExistsNetFramework()         {             bool flag = false;             RegistryKey rk = Registry.LocalMachine;             RegistryKey framework4 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\.NETFramework\\policy\\v4.0\\");             RegistryKey framework35 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\.NETFramework\\policy\\v3.5\\");             RegistryKey framework31 = rk.OpenSubKey(@"SOFTWARE\\Microsoft\\.NETFramework\\policy\\v3.2\\");             if (framework4 != null)             {                 flag = true;                 return flag;             }             return flag;         }         #endregion

程序基本大体完成,但是还是有很多问题没有解决:

1.读写表的时候是"Sheet1",如果没有的excel中没有的话,这里应该要加一个try...catch 捕获异常。

2.其中牵涉到一个office2003和2007以后的版本问题。如果今后又有office2014之类的如何动态处理。

3.判断office版本和net framework 版本只能通过注册表吗,还有其他有效的方法。Environment.Version只能得到net framework一个版本。

4.做成安装包的时候这个如何把net framework4.0 静默安装,这个看到有,还没做。

抱歉!评论已关闭.