using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Collections;

namespace yinLouSys.code
{
    //======================================================================
    //
    //        Copyright (C) 2007-2011 创新合力
    //        All rights reserved
    //
    //        filename : ExcelTrue.cs
    //        description :
    //
    //        created by 潘俊兴 at 2011-8-16
    //
    //======================================================================

    public class ExcelTrue
    {
        private string _fileName;


        public ExcelTrue(string fn)
        {
            _fileName = fn;
        }

        public ExcelTrue()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 导出DataTable中的数据
        /// </summary>
        /// <param name="fileName">保存路径</param>
        /// <param name="dt">DataTable数据</param>
        /// <returns>是否成功</returns>
        public static bool Export(string fileName, DataTable dt)
        {
            bool isSuccess = false;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = false;
            object ms = Type.Missing;
            Microsoft.Office.Interop.Excel.Workbook wk = excel.Workbooks.Add(ms);
            Microsoft.Office.Interop.Excel.Worksheet ws = wk.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ws.Cells[1, i + 1] = dt.Columns[i].ColumnName;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ws.Cells[i + 2, j + 1] = "'" + dt.Rows[i][j].ToString();
                }
            }
            try
            {
                wk.SaveAs(fileName, ms, ms, ms, ms, ms, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, ms, ms, ms, ms, ms);
                isSuccess = true;
            }
            catch (Exception)
            {
                isSuccess = false;
            }
            excel.Quit();
            return isSuccess;
        }

        public static bool Export(string fileName, DataGridView dt)
        {
            bool isSuccess = false;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = false;
            object ms = Type.Missing;
            Microsoft.Office.Interop.Excel.Workbook wk = excel.Workbooks.Add(ms);
            Microsoft.Office.Interop.Excel.Worksheet ws = wk.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                if (dt.Columns[i].Visible)
                    ws.Cells[1, i + 1] = dt.Columns[i].Name;
            }

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    if (dt.Columns[j].Visible)
                        ws.Cells[i + 2, j + 1] = "'" + ((dt.Rows[i].Cells[j].Value==null || dt.Rows[i].Cells[j].Value is DBNull)?"":dt.Rows[i].Cells[j].Value.ToString());
                }
            }
            try
            {
                wk.SaveAs(fileName, ms, ms, ms, ms, ms, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, ms, ms, ms, ms, ms);
                isSuccess = true;
            }
            catch (Exception)
            {
                isSuccess = false;
            }
            excel.Quit();
            return isSuccess;
        }

        /// <summary>
        /// 从DataGridView导出到Excel
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="dv">DataGridView控件对象</param>
        /// <param name="outIndexs">需要导出的行索引,null表示全部(int)</param>
        /// <param name="noColIndex">不需要导出的列索引,null表示全部(int)</param>
        public static bool ExcelOfDataGirdView(string filePath, DataGridView dv, string[] outIndexs, ArrayList noColIndex)
        {

            string strFileName = filePath;
            if (System.IO.File.Exists(strFileName))
            {
                System.IO.File.Delete(strFileName);
            }

            bool isSuccess = false;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = false;
            object ms = Type.Missing;
            Microsoft.Office.Interop.Excel.Workbook wk = excel.Workbooks.Add(ms);
            Microsoft.Office.Interop.Excel.Worksheet ws = wk.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;

            DataTable tabM = (DataTable)dv.DataSource;
            if (noColIndex == null)
            {
                for (int i = 0; i < tabM.Columns.Count; i++)
                {
                    ws.Cells[1, i + 1] = tabM.Columns[i].ColumnName;
                }
            }
            else
            {
                for (int i = 0; i < tabM.Columns.Count; i++)
                {
                    if (noColIndex != null && noColIndex.Contains(i))
                    {
                        continue;
                    }
                    ws.Cells[1, i + 1] = tabM.Columns[i].ColumnName;
                }
            }

            if (outIndexs == null)
            {
                for (int i = 0; i < tabM.Rows.Count; i++)
                {
                    for (int j = 0; j < tabM.Columns.Count; j++)
                    {
                        if (noColIndex != null && noColIndex.Contains(j))
                        {
                            continue;
                        }
                        ws.Cells[i + 2, j + 1] = "'" + tabM.Rows[i][j].ToString();
                    }
                }
            }
            else
            {
                for (int i = 0; i < outIndexs.Length; i++)
                {

                    for (int j = 0; j < tabM.Columns.Count; j++)
                    {
                        if (noColIndex != null && noColIndex.Contains(j))
                        {
                            continue;
                        }
                        string showVal = ("联系电话" == tabM.Columns[j].ColumnName) ? GetFirstTel(dv.Rows[int.Parse(outIndexs[i])].Cells[j].Value.ToString()) : dv.Rows[int.Parse(outIndexs[i])].Cells[j].Value.ToString();


                        ws.Cells[i + 2, j + 1] = "'" + showVal;

                    }

                }
            }

            try
            {
                wk.SaveAs(filePath, ms, ms, ms, ms, ms, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, ms, ms, ms, ms, ms);
                isSuccess = true;
            }
            catch (Exception)
            {
                isSuccess = false;
            }
            excel.Quit();
            return isSuccess;
        }


        /// <summary>
        /// 从电话字符串截取第一个电话号码
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        private static string GetFirstTel(string val)
        {
            string temp = val.Trim().Replace(" ", "#").Replace(",", "#").Replace("，", "#");
            string[] tels = temp.Split('#');

            return (tels.Length > 0) ? tels[0] : val;
        }


        //获取Excel获取工作表
        private string[] GetExcelSheetNames()
        {
            OleDbConnection objConn = null;
            System.Data.DataTable dt = null;
            try
            {
                // Connection String. Change the excel file to the file you
                // will search.
                String connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                "Data Source=" + _fileName + ";Extended Properties=Excel 8.0;";
                // Create connection object by using the preceding connection string.
                objConn = new OleDbConnection(connString);
                // Open connection with the database.
                objConn.Open();
                // Get the data table containg the schema guid.
                dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                if (dt == null)
                {
                    return null;
                } String[] excelSheets = new String[dt.Rows.Count];
                int i = 0;    // Add the sheet name to the string array.
                foreach (DataRow row in dt.Rows)
                {
                    excelSheets[i] = row["TABLE_NAME"].ToString();
                    i++;
                }    // Loop through all of the sheets if you want too...
                for (int j = 0; j < excelSheets.Length; j++)
                {
                    // Query each excel sheet.
                } return excelSheets;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
                // Clean up.
                if (objConn != null)
                {
                    objConn.Close();
                    objConn.Dispose();
                }
                if (dt != null)
                {
                    dt.Dispose();
                }
            }
        }

        /// <summary>
        /// 获取Excel内容
        /// </summary>
        /// <returns></returns>
        public DataSet LoadDataFromExcel()
        {
            try
            {
                string[] mmGG = GetExcelSheetNames();
                string sheet = mmGG[0].Replace("Print_Area", "").Replace("$", "");

                string strConn;
                strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
                OleDbConnection OleConn = new OleDbConnection(strConn);
                OleConn.Open();
                String sql = "SELECT * FROM  [" + sheet + "$]";//可是更改Sheet名称，比如sheet2，等等 
                //String sql = "SELECT * FROM  [" + sheet + "]";

                OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);


                DataSet OleDsExcle = new DataSet();
                OleDaExcel.Fill(OleDsExcle, sheet);
                OleConn.Close();
                return OleDsExcle;
            }
            catch (Exception err)
            {
                return null;
            }
        }

        public DataTable GetLoadFromFile(string file)
        {
            try
            {
                String line;
                String[] split = null;
                DataTable table = new DataTable("auto");
                DataRow row = null;
                StreamReader sr = new StreamReader(file, System.Text.Encoding.Default);
                //创建与数据源对应的数据列 
                line = sr.ReadLine();
                split = Regex.Replace(line, @"\s+", ",").Split(',');
                foreach (String colname in split)
                {
                    table.Columns.Add(colname, System.Type.GetType("System.String"));
                }
                //将数据填入数据表 
                int j = 0;
                while ((line = sr.ReadLine()) != null)
                {

                    if ("" == line.Trim())
                    {
                        continue;
                    }

                    j = 0;
                    row = table.NewRow();
                    split = Regex.Replace(line, @"\s+", ",").Split(',');
                    foreach (String colname in split)
                    {
                        if (j >= split.Length)
                        {
                            break;
                        }
                        row[j] = colname;
                        j++;
                    }
                    table.Rows.Add(row);
                }
                sr.Close();

                return table;
            }
            catch
            {
                throw;
            }

        }
    }
}
