1. 程式人生 > >OleDb匯入資料到Excel,跨過Com元件

OleDb匯入資料到Excel,跨過Com元件

此種方式匯入Excel,不支援對Excel單元格進行操作
   #region 變數
        //Excel 2007檔案
        private static string _connString2007 = string.Empty;
        private static string str2007 = @"Provider=Microsoft.ACE.OLEDB.12.0;data source={0};Extended Properties='Excel 12.0 XML;HDR=Yes;'";

        //Excel 2003檔案
        private static string _connString2003 = string.Empty;
        private static string str2003 = @"Provider=Microsoft.Jet.OleDb.4.0;data source={0};Extended Properties='Excel 8.0;HDR=Yes;'";

        //OleDbConnection物件
        private static OleDbConnection _oleDBConn;
        #endregion
        #region 開啟及關閉
        /// <summary>
        /// 開啟Excel連結
        /// </summary>
        /// <param name="dbName"></param>
        public static void OpenExcelDB(string dbName)
        {
            FileInfo fileInfo = new FileInfo(dbName);
            try
            {
                switch (fileInfo.Extension.ToLower())
                {
                    case ".xls":
                        _connString2003 = string.Format(str2003, dbName);
                        _oleDBConn = new OleDbConnection(_connString2003);
                        break;
                    case ".xlsx":
                        _connString2007 = string.Format(str2007, dbName);
                        _oleDBConn = new OleDbConnection(_connString2007);
                        break;
                    default: break;
                }
            }
            catch
            {
                _oleDBConn = null;
            }
        }

        /// <summary>
        /// 關閉Excel連結
        /// </summary>
        public static void CloseExcelDB()
        {
            if (_oleDBConn != null && _oleDBConn.State == ConnectionState.Open)
            {
                _oleDBConn.Close();
                _oleDBConn.Dispose();
            }
        }
        #endregion

        #region 匯出資料到Excel

        /// <summary>
        /// 建立Excel路徑
        /// </summary>
        public static string OpenSaveFolderBrowserDialog()
        {
            SaveFileDialog fd = new SaveFileDialog();
            fd.Filter = "EXCEL檔案(*.xls)|*.xls|EXCEL檔案(*.xlsx)|*.xlsx";
            fd.FileName = "新建 Microsoft Excel 工作表";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                return fd.FileName;
            }

            return string.Empty;
        }

        /// <summary>
        /// 建立表頭語句
        /// </summary>
        /// <param name="sheetName">Excel中sheet名</param>
        /// <param name="heads">Excel欄位名</param>
        public static string GetCreateTableCmdText(string sheetName,string[] heads)
        {
            StringBuilder cmdText = new StringBuilder() ;
            
            cmdText.Append(string.Format("CREATE TABLE [{0}] (", sheetName));

            foreach (string headName in heads)
            {
                cmdText.Append(string.Format("[{0}] VarChar,", headName));
            }

            cmdText = cmdText.Remove(cmdText.Length - 1, 1);

            cmdText.Append(")");

            return cmdText.ToString();
        }

        /// <summary>
        /// 建立插值語句
        /// </summary>
        /// <param name="sheetName">Excel中待插值的sheet名</param>
        /// <param name="values">待插入的值</param>
        /// <returns></returns>
        public static string GetInsertValueCmdText(string sheetName,string[] values)
        {
            StringBuilder cmdText = new StringBuilder();
            
            cmdText.Append(string.Format("INSERT INTO {0} VALUES (", sheetName));

            foreach (string value in values)
            {
                cmdText.Append(string.Format("'{0}',",value));
            }

            cmdText = cmdText.Remove(cmdText.Length - 1, 1);

            cmdText.Append(")");

            return cmdText.ToString();
        }

        /// <summary>
        /// 匯出資料到Excel
        /// </summary>
        /// <param name="sheetName">sheet名</param>
        /// <param name="heads">表頭</param>
        /// <param name="values">於表頭對應的值</param>
        public static void WriteDataToExcel(string sheetName,string[] heads,List<string[]> values)
        {
            string filePath = OpenSaveFolderBrowserDialog();
            if (string.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("未獲取到正確Excel路徑");
                return;
            }

            OpenExcelDB(filePath);
            if (_oleDBConn == null)
            {
                MessageBox.Show("Excel連結失敗");
                return;
            }

            _oleDBConn.Open();
            OleDbCommand cmd = new OleDbCommand { Connection = _oleDBConn};

            try
            {
                cmd.CommandText = GetCreateTableCmdText(sheetName, heads);
                cmd.ExecuteNonQuery();
            }
            catch (Exception exc)
            {
                MessageBox.Show(string.Format("表頭插入失敗: ", exc.Message));
                return;
            }

            StringBuilder valueError = new StringBuilder();
            foreach (string[] value in values)
            {
                try
                {
                    cmd.CommandText = GetInsertValueCmdText(sheetName, value);
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    valueError.Append(string.Format("插值失敗 表名:{0} 行數:{1} /n", sheetName, values.IndexOf(value)));
                    continue;
                }
            }



            if (string.IsNullOrEmpty(valueError.ToString()))
            {
                MessageBox.Show("匯入成功");
            }
            else
            {
                MessageBox.Show(valueError.ToString());
            }

            CloseExcelDB();
        }

        #endregion