14
2012
04

Excel导入到数据库及写回操作记录到Excel中

在导入Excel时,主要使用读取Excel文件内容的查询语句,写回Excel时,需要激活Excel文件,再对里面内容进行修改或填充,操作完成后保存Excel,关闭释放Excel资源:

//引入命名空间
using System.Data.OleDb;
using System.Collections;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Runtime.InteropServices;
///<summary>
///浏览需要导入的Excel文件
///</summary>
private void OpenFile()
        {
            textBox1.Text = "";
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "2003 Excel 文件(*.xls)|*.xls|2007 Excel 文件(*.xlsx)|*.xlsx";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                sFileName = openFileDialog1.FileName;
                textBox1.Text = sFileName.ToString();//将要导入文件路径存入到文本框中
            }
        }
 
///<summary>
///导入的Excel文件按钮
///</summary>
private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() != "")
            {
                //获取Excel的文件后缀名
                string ss = sFileName.Replace("\\", "$");
                string[] tt = ss.Split('$');
                string yy = tt[tt.Length - 1];
                string[] zz = yy.Split('.');
                string type = "." + zz[zz.Length - 1];
 
                //通过Excel的文件类型,判断使用数据连接字符串
                string FilePath = getStrCon(sFileName, type);
 
                if (FilePath != "")
                {
                    try
                    {
                        //创建Excel数据连接
                        OleDbConnection OleDbxls = new OleDbConnection(FilePath);
                        OleDbxls.Open(); //Excel数据连接打开
 
                        //返回Excel的架构,包括各个sheet表的名称,类型,创建时间和修改时间等
                        System.Data.DataTable dtSheetName = OleDbxls.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                        //包含excel中表名的字符串数组
                        string[] strTableNames = new string[dtSheetName.Rows.Count];
                        for (int k = 0; k < dtSheetName.Rows.Count; k++)
                        {
                            strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString(); //获取Excel表中的表名
                        }
 
                        OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [" + strTableNames[0] + "]", OleDbxls);   //使用Excel表中的第一个表查询里面的数据
                        OleDbxls.Close();
                        DataSet ds = new DataSet();
                        List<TableInfo> LtableInfo = new List< TableInfo >(); //创建存储数据的实体类集合
 
                        myDa.Fill(ds, "TableInfo"); //将Excel表中数据填充到数据集中
 
                        foreach (DataRow dr in ds.Tables["TableInfo"].Rows)
                        {
                            TableInfo tableInfo= new TableInfo();
                            tableInfo.Name = dr["FieldName"].ToString(); //通过Excel表中字段进行读取字段对应的值
                            //通过Excel表中字段读取所有值
 
                            if (tableInfo!= null)
                            {
                                LtableInfo.Add(tableInfo); //将实体类对应的数据添加到实体类集合列表中
                            }
                        }
 
                        if (LtableInfo != null)
                        {
                            try
                            {
                                Excel = new Microsoft.Office.Interop.Excel.Application(); //实例化Excel对象,对Excel表中数据进行操作
                                xBook = Excel.Workbooks._Open(sFileName,
                                    Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                                    , Missing.Value, Missing.Value, Missing.Value, Missing.Value); //打开Excel的表对象,后面对Excel表中数据进行操作
 
 
                                xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1]; //获取Sheets1表
 
                                xSheet.Activate(); //激活当前工作溥
 
                                int Count = LtableInfo.Count; //获取读取Excel中数据条数
 
                                for (int i = 0; i < LtableInfo.Count; i++)
                                {  
                                    if (LtableInfo!= null && LtableInfo [i]. Name!= "")
                                    {
                                           //对数据进行存储到数据库中
                                    }
 
                                    //操作完成后,在当前工作溥写入操作记录内容
                                    xSheet.Cells[i + 2, 7] = DateTime.Now; //写入操作时间到操作记录内容中
                                    //可以写入其他的内容到Excel其他列中
                                    progressBar1.Value = (i + 1) * 100 / (Count); //进度条显示情况
                                    //label1.Text = progressBar1.Value.ToString() + "%"; //显示进度百分比
                                }
 
                                //保存目标文件           
                                xBook.Save();
                            }
                            catch
                            {
 
                            }
                            finally
                            {
                                //设置DisplayAlerts
                                Excel.DisplayAlerts = false;
                                Excel.Visible = true;
 
                                KillSpecialExcel();//关闭创建的Excel进程
 
                                //释放对象
                                if (xSheet != null)
                                {
                                    xSheet = null;
                                }
                                if (xBook != null)
                                {
                                    xBook = null;
                                }
                                if (Excel != null)
                                {
                                   Excel = null;
                                }
 
                                //释放内存
                                GcCollect();
                            }
                        }
                    }
                    catch
                    {
                        MessageBox.Show("导入出错!");
                    }
                    finally
                    {
                    }
                }
                else
                {
                    MessageBox.Show("导入文件格式不正确!");
                }
            }
            else
            {
                MessageBox.Show("请先选择导入文件!");
            }
            MessageBox.Show("导入完成!");
        }
 
[DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
        ///<summary>
        ///关闭Excel进程
        ///</summary>
        public static void KillSpecialExcel()
        {
            try
            {
                if (Excel != null)
                {
                    IntPtr t = new IntPtr(Excel.Hwnd);   //得到这个句柄,具体作用是得到这块内存入口
 
                    int k = 0;
                    GetWindowThreadProcessId(t, out k);   //得到本进程唯一标志k
                    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);   //得到对进程k的引用
                    p.Kill();     //关闭进程k
                }
            }
            catch
            {
                MessageBox.Show("关闭进程时出错!");
            }
        }
 
        ///<summary>
        ///释放内存
        ///</summary>
        public void GcCollect()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
 
        ///<summary>
        ///根据Excel文件类型判断
        ///</summary>
        ///<param name="strPath"></param>
        ///<param name="type"></param>
        ///<returns></returns>
        private static string getStrCon(string strPath, string type)
        {
            string strConn2007 = "Provider = MICROSOFT.Ace.OleDb.12.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'";
            string strCon2003 = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
            if (type == ".xls")
            {
                return strCon2003;
            }
            else if (type == ".xlsx")
            {
                return strConn2007;
            }
            else
            {
                return "";
            }
        }
« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。