• C# WinFrom 用Execl做模版进行数据导入


          为了方便数据的导入,写一个通用的数据库导入方法进行导入数据会节省很大的时间,有的客户有很多的Execl,几个还好,如果多了有几百种表各种格式的表格都有,如果一个个来进行数据导入那是一个相当大的工作,写代码要每个都写一个,完了客户需求在进行变更,表格在进行改变,那代码修改量是相当大的,闹不好要死人撒,o(∩_∩)o 哈哈……懒人总会有懒的思维方式,嘿嘿……

          大体的思维方式如下:

          一、先创建一个Execl文件模版。在里面进行编辑一个模版,大家都知道Execl里面有公式的,从一个表里面引用其他表的数据是可以实现,这样我们把客户的表弄成跟我们模版相对应的表格,在把客户的表格用公式进行替换到其他的表格里面,在其他的表格里面我们写成利于我们进行编程的竖向表格化数据。模版的的sheet表面和里面的字段完全和数据库里面的字段一一对应。

         二、编写code用代码实现导入的步骤。

        (1)将创建的模版copy到临时文件夹里面

        (2)将客户要导入的数据的sheet表copy到临时文件夹里面的模板里

        (3)读取新模版里面的表格数据到Datatable

        (4)获取Datatable里面的表名和列名生成相应的sql语句

        (5)将Datatable里面数据进行循环去执行生成的sql将数据导入到创建好的数据库。

         思路就是上面那样,具体实现如下面的Code所示:

          引入一下命名空间

          using Excel = Microsoft.Office.Interop.Excel;
          using System.IO;
          using System.Data.OleDb;

         具体只要代码如下:

            private void btn_copyToM_Click(object sender, EventArgs e)
            {
                //将模版copy到临时文件路径下
                string tempPath = Application.StartupPath+"//temp//";
                fileName = tempPath +"result_temp.xls";
                string strDataFile = txt_filename.Text.Trim();
                if(!System.IO.Directory.Exists(tempPath))
                {
                    Directory.CreateDirectory(tempPath);
                }
                //判断是否存在模版文件
                string modlPath=Application.StartupPath+"//mold//result.xls";
                if (File.Exists(modlPath))
                {
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }
                    File.Copy(modlPath, fileName);
                }
                label1.Text = fileName;

               // Excel.Range objRange = null;

                Excel.Application objExcel = new Excel.Application();

                Excel.Workbook objWorkBookMold = null;

                Excel.Workbook objWorkBookData = null;

                objExcel.Workbooks.Open(fileName);

                objWorkBookMold=objExcel.Workbooks[1];

                objExcel.Workbooks.Open(strDataFile);

                objWorkBookData=objExcel.Workbooks[2];


                Excel.Worksheet objSheetData =objWorkBookData.Sheets[1];
                Excel.Worksheet objSheetMold = objWorkBookMold.Sheets[1];

                objSheetData.UsedRange.Copy();
                objSheetMold.Range["A1"].PasteSpecial();


                objWorkBookMold.Save();

                objWorkBookMold.Close(true, Type.Missing, Type.Missing);
                objWorkBookMold = null;
                objWorkBookData.Close(true, Type.Missing, Type.Missing);
                objWorkBookData = null;


                objExcel.Quit();
                objExcel = null;

                //Thread.Sleep(2000);

               // File.Delete(filename);
            }

            /// <summary>
            /// 查找指定表里面的指定数据
            /// </summary>
            /// <param name="path"></param>
            /// <param name="tableName"></param>
            /// <returns></returns>
            DataTable GetDataByExcel(string path,string tableName)
            {
                string sqlconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0";
                string sql = "SELECT  * FROM [" + tableName + "$] ";
                DataTable dtda = new DataTable();
                using (OleDbCommand oldcom = new OleDbCommand(sql, new OleDbConnection(sqlconn)))
                {
                    OleDbDataAdapter oleda = new OleDbDataAdapter(oldcom);
                    dtda.TableName = tableName;
                    oleda.Fill(dtda);
                }
                return dtda;
            }

           

            /// <summary>
            /// 通过数据表获取表的名字和字段名称
            /// </summary>
            /// <param name="data"></param>
            void getDataMsg(DataTable data)
            {
                fileTableName = data.TableName;
                fileTableColunmsName=new string[data.Columns.Count];
                for (int i = 0; i < fileTableColunmsName.Length; i++)
                {
                    fileTableColunmsName[i] = data.Columns[i].ColumnName;
                }

            }

             /// <summary>
            /// 获取模版里面的所有的表名
            /// </summary>
            /// <param name="path"></param>
            /// <returns></returns>
            string[] GetTabaleNames(string path)
            {
                Excel.Application objExcel = new Excel.Application();
                objExcel.Workbooks.Open(path);
                string[] strTableName = new string[objExcel.Workbooks[1].Worksheets.Count];
                for (int i = 0; i < strTableName.Length; i++)
                {
                    Excel.Worksheet sheet= objExcel.Workbooks[1].Worksheets[i + 1];
                    strTableName[i] =sheet.Name;
                    sheet = null;
                }
                objExcel.Quit();
                objExcel = null;
                return strTableName;
            }

           private void btn_sql_Click(object sender, EventArgs e)
            {
                StringBuilder sbSql = new StringBuilder();
                sbSql.Append("insert into "+fileTableName+" ");
                sbSql.Append("( ");
                if (fileTableColunmsName != null)
                {
                    if (fileTableColunmsName.Length > 0)
                    {
                        for (int i = 0; i < fileTableColunmsName.Length; i++)
                        {
                            if (i == 0)
                            {
                                sbSql.Append(fileTableColunmsName[i]);
                            }
                            else
                            {
                                sbSql.Append("," + fileTableColunmsName[i]);
                            }
                        }
                        sbSql.Append(")");
                        sbSql.Append("values ");
                        sbSql.Append("(");
                        for (int i = 0; i < fileTableColunmsName.Length; i++)
                        {

                            if (i == 0)
                            {
                                sbSql.Append("@" + fileTableColunmsName[i]);
                            }
                            else
                            {
                                sbSql.Append(",@" + fileTableColunmsName[i]);
                            }
                        }
                    }
                }
                sbSql.Append(")");
            }

    o(∩_∩)o 哈哈以上面的方式进行导入数据,不管你有多少表格了,俺们苦逼的程序员将不在进行编写Code了,只要把模版改改就OK了!

  • 相关阅读:
    银行存钱取钱余额的图形程序
    centos7 的httpd的问题
    idea创建springboot项目初始化失败解决方案
    Spring Boot之yaml配置注入基本使用
    idea修改Java注释的颜色
    IDEA常用快捷键及修改快捷键
    WordPress Markdown编辑器插件:WP Githuber MD
    Docker安装solo博客部署到云服务器教程
    Spring Boot 定制个性 banner
    Java类型转换
  • 原文地址:https://www.cnblogs.com/mingyan/p/2428035.html
Copyright © 2020-2023  润新知