Gridcontrol导出Execl

 /// <summary>
        /// 新建Excel(新增)
        /// </summary>
        /// <returns></returns>
        public bool CreateExcel()
        {
            //新建Excel并添加5个sheet
            bool isSucc = true;
            try {
                //新建Excel并建5个sheet
                ArrayList arr = new ArrayList();
                string sqlcam = @"create table 新建推广计划([推广计划名称(必填)] varchar(100),[推广计划每日预算(选填)] tinyint,[推广计划推广地域(选填)] memo,[参与网盟推广(必填)] varchar(10),[网盟推广出价(参与网盟推广时必填)] tinyint)";
                string sqladgroup = @"create table 新建推广单元([推广计划名称(必填)] varchar(100),[推广单元名称(必填)] varchar(100),[推广单元出价(必填)] tinyint)";
                string sqlcreative = @"create table 新增文字广告([推广计划名称(必填)] varchar(100),[推广单元名称(必填)] varchar(100),[文字广告标题(必填)] varchar(100),[文字广告描述1(必填)] varchar(100),[文字广告描述2(选填)]  varchar(100),[显示URL(选填)] varchar(100),[访问URL(必填)] memo)";
                string sqlkey = @"create table 新增关键词([推广计划名称(必填)] varchar(100),[推广单元名称(必填)] varchar(100),[关键词(必填)] varchar(100),[关键词匹配模式(必填)] varchar(30),[关键词出价(选填)] tinyint,[访问URL(选填)] memo)";
                string sqlaccount = @"create table 设置搜索推广专业版每日预算、推广地域([搜索推广专业版预算(选填)] varchar(50),[搜索推广专业版地域(选填)] memo)";
                arr.Add(sqlcam);
                arr.Add(sqladgroup);
                arr.Add(sqlcreative);
                arr.Add(sqlkey);
                arr.Add(sqlaccount);
                InsertExcel(arr);
            }catch(Exception e)
            {
                MessageBox.Show(this, "抱歉,操作失败,请检查你的Excel是否安装的有问题        /n", "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                isSucc = false;
            }
            return isSucc;
        }

/// <summary>
        /// 将推广计划插入Excel的第一个Sheet
        /// </summary>
        void ExportCampaign()
        {
            try
            {
                #region 插入账户信息
                string userName="";
                if(Config.UName!="")
                {
                    userName = Config.UName;
                }
                string accountsql = string.Format("select budget,citytarget from baccount where userName='{0}'", userName);
                DataRow accountRow = DataBase.ExecuteDataSet(accountsql, "2").Tables[0].Rows[0];
                string budget=accountRow["budget"].ToString();
                if(budget=="0")
                {
                    budget="";
                }
                string region1= accountRow["citytarget"].ToString().Replace("//r",",");
                if(region1!="" && region1.Contains(",") && region1.LastIndexOf(',')==region1.Length-1)
                {
                    region1=region1.Substring(0,region1.Length-1);
                }
                string sqlaccount = string.Format("insert into [设置搜索推广专业版每日预算、推广地域$] (搜索推广专业版预算(选填),搜索推广专业版地域(选填)) values('{0}','{1}')",budget ,region1);
                ArrayList arraccount = new ArrayList();
                arraccount.Add(sqlaccount);
                InsertExcel(arraccount);
                #endregion

                //一次查询一万条(推广计划)
                for (int a = 0; a < camcount; )
                {
                    DataSet ds = new DataSet();
                    string sqlcampaign = string.Format(@"select CampaignName,budget,RegionTarget,
                                                         case when JoinCpro='False' then '不参与' else '参与' end as JoinCpro,
                                                         case when JoinCpro='False' then '' else lower(CproPrice) end as CproPrice
                                                         from icpcampaign order by LocalId limit {1}  offset {0}", a,count1);
                    ds = DataBase.ExecuteDataSet(sqlcampaign, "1");

                    int totalcount = ds.Tables[0].Rows.Count;
                    int bn = 0;
                    int en = count2;
                    if (totalcount < count2)
                        en = totalcount;
                    for (int i = bn; i < en; )
                    {
                        ArrayList arrcampaign = new ArrayList();
                        for (int j = bn; j < en; j++)
                        {
                            DataRow row = ds.Tables[0].Rows[j];
                            //推广地域
                            string region=row["RegionTarget"].ToString().Replace("//r",",");
                            if(region!="" && region.Contains(",") && region.LastIndexOf(',')==region.Length-1)
                            {
                                region=region.Substring(0,region.Length-1);
                            }
                            //每日预算
                            string budget1=row["Budget"].ToString();
                            if(budget1=="")
                            {
                                budget1 = "0";
                            }
                            //网盟出价
                            string cproPrice=row["CproPrice"].ToString();
                            if(cproPrice=="")
                            {
                                cproPrice="0";
                            }
                            string sql = string.Format("insert into [新建推广计划$] (推广计划名称(必填),推广计划每日预算(选填),推广计划推广地域(选填),参与网盟推广(必填),网盟推广出价(参与网盟推广时必填)) values ('{0}',{1},'{2}','{3}',{4})",
                            Strings.InputText(row["CampaignName"].ToString()),budget1, region, row["JoinCpro"].ToString(),cproPrice);
                            arrcampaign.Add(sql);
                            i++;
                        }
                        InsertExcel(arrcampaign);
                        bn = en;
                        lblCamCount.Text = (a + en) + "";
                        allcount += arrcampaign.Count;
                        proPercent.Value = allcount;
                        if (totalcount - en >= count2)
                        {
                            en += count2;
                        }
                        else
                        {
                            en = totalcount;
                        }
                    }
                    a += count1;
                }
                clcount++;
                SetHeader();
            }catch(Exception e)
            {
               
            }
        }

 

/// <summary>
        /// 向Excel中插入数据
        /// </summary>
        /// <param name="sql">语句</param>
        public void InsertExcel(ArrayList arr)
        {
            //用2003的dll不会出问题,用2007的写入的字符度会有所限限,不能超过255
            //string strCon = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=yes;IMEX=0'", path);//2007
            string strCon = string.Format(@"Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = {0};Extended Properties='Excel 8.0;HDR=yes;IMEX=0'", path);//2003
            try
            {
                //创建一个数据链接
                using (OleDbConnection myConn = new OleDbConnection(strCon))
                {
                    myConn.Open();
                    //打开数据链接
                    try
                    {
                        foreach (string s in arr)
                        {
                            OleDbCommand cmd = new OleDbCommand(s, myConn);
                            cmd.ExecuteNonQuery();
                            cmd.Dispose();
                        }
                    }
                    catch (OleDbException e2)
                    {
                        arrerror.Add(e2.Message.ToString());
                    }
                }
            }
            catch (Exception e1)
            {
                arrerror.Add(e1.Message.ToString());
            }
        }

 

        //关闭当前的进程      
        [DllImport("User32.dll",   CharSet   =   CharSet.Auto)]  
        public static extern int GetWindowThreadProcessId(IntPtr hwnd,out int ID);
        public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
        {  
            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
      }

        /// <summary>
        /// 检查本机Excel版本
        /// </summary>
        /// <returns></returns>
        public int CheckOfficeVersion()
        {
            int excelType = 0;//0表示没有 2007:安装的2007 2003:安装的2003
            string file = "";//Excel文件安装路径
            Type type = Type.GetTypeFromProgID("Excel.Application");
            if (type != null)
            {
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey akey = rk.OpenSubKey(@"SOFTWARE//Microsoft//Office//11.0//Excel//InstallRoot//");//Office2003
                RegistryKey akeytwo = rk.OpenSubKey(@"SOFTWARE//Microsoft//Office//12.0//Excel//InstallRoot//");//Office2007

                if (akey != null)
                {
                    file = akey.GetValue("Path").ToString();
                    if (File.Exists(file + "Excel.exe"))
                        excelType = 2003;
                }
                if (akeytwo != null)
                {
                    file = akeytwo.GetValue("Path").ToString();
                    if (File.Exists(file + "Excel.exe"))
                        excelType = 2007;
                }
            }
            ProcessStartInfo info = new ProcessStartInfo(file + "Excel.exe");
            return excelType;
        }

 

  /// <summary>
        /// 设置表头
        /// </summary>
        public void SetHeader()
        {
            if (clcount == 4)
            {
                try
                {
                    Microsoft.Office.Interop.Excel.Application excel = new ApplicationClass();
                    excel.Visible = false; //使Excel不可视 
                    //设置禁止弹出保存和覆盖的询问提示框
                    excel.DisplayAlerts = false;
                    excel.AlertBeforeOverwriting = true;
                    Workbook book = excel.Workbooks.Open(path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

                    #region 设置表头字体颜色、批注
                    //第一个Sheet 设置背景颜色和字体颜色
                    Worksheet sheet1 = (Worksheet)book.Worksheets[1];
                    Range ranges1 = sheet1.get_Range(sheet1.Cells[1, 1], sheet1.Cells[1, 5]);
                    ranges1.Interior.Color = System.Drawing.Color.FromArgb(198, 239, 206).ToArgb();
                    ranges1.Font.Color = System.Drawing.Color.FromArgb(0, 128, 0).ToArgb();
                    //加批注
                    Range range12 = sheet1.Cells[1, 2] as Range;
                    range12.AddComment("百度推广平台提示:/n不填写时默认为“不限定预算”");
                    range12.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range12.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range13 = sheet1.Cells[1, 3] as Range;
                    range13.AddComment("百度推广平台提示:/n不填写时默认沿用账户地域;填写“全部地域”,计划则单独设置为可在全部地域进行推广");
                    range13.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range13.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range14 = sheet1.Cells[1, 4] as Range;
                    range14.AddComment("百度推广平台提示:/n请填写'参与'或'不参与'");
                    range14.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range14.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range15 = sheet1.Cells[1, 5] as Range;
                    range15.AddComment("百度推广平台提示:/n参与网盟推广的出价");
                    range15.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range15.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;

                    //第二个Sheet 推广单元 设置背景颜色和字体颜色
                    Worksheet sheet2 = (Worksheet)book.Worksheets[2];
                    Range ranges2 = sheet2.get_Range(sheet2.Cells[1, 1], sheet2.Cells[1, 3]);
                    ranges2.Interior.Color = System.Drawing.Color.FromArgb(198, 239, 206).ToArgb();
                    ranges2.Font.Color = System.Drawing.Color.FromArgb(0, 128, 0).ToArgb();
                    //加批注
                    Range range21 = sheet2.Cells[1, 1] as Range;
                    range21.AddComment("百度推广平台提示:/n请填写您新增推广单元所属的推广计划");
                    range21.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range21.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;

                    //第三个Sheet 文字广告 设置背景颜色和字体颜色
                    Worksheet sheet3 = (Worksheet)book.Worksheets[3];
                    Range ranges3 = sheet3.get_Range(sheet3.Cells[1, 1], sheet3.Cells[1, 7]);
                    ranges3.Interior.Color = System.Drawing.Color.FromArgb(198, 239, 206).ToArgb();
                    ranges3.Font.Color = System.Drawing.Color.FromArgb(0, 128, 0).ToArgb();
                    //加批注
                    Range range31 = sheet3.Cells[1, 1] as Range;
                    range31.AddComment("百度推广平台提示:/n请填写您新增推广单元所属的推广计划");
                    range31.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range31.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range32 = sheet3.Cells[1, 2] as Range;
                    range32.AddComment("百度推广平台提示:/n请填写您新增文字广告所属的推广单元");
                    range32.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range32.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range33 = sheet3.Cells[1, 3] as Range;
                    range33.AddComment("百度推广平台提示:/n文字广告标题最大长度为50个字符");
                    range33.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range33.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range34 = sheet3.Cells[1, 4] as Range;
                    range34.AddComment("百度推广平台提示:/n文字广告描述1最大长度为80个字符");
                    range34.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range34.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range35 = sheet3.Cells[1, 5] as Range;
                    range35.AddComment("百度推广平台提示:/n文字广告描述2最大长度为80个字符");
                    range35.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range35.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range36 = sheet3.Cells[1, 6] as Range;
                    range36.AddComment("百度推广平台提示:/n显示URL最大长度为36个字符");
                    range36.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range36.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range37 = sheet3.Cells[1, 7] as Range;
                    range37.AddComment("百度推广平台提示:/n访问URL最大长度为1017个字符");
                    range37.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range37.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;

                    //第四个Sheet 关键词 设置背景颜色和字体颜色
                    Worksheet sheet4 = (Worksheet)book.Worksheets[4];
                    Range ranges4 = sheet4.get_Range(sheet4.Cells[1, 1], sheet4.Cells[1, 6]);
                    ranges4.Interior.Color = System.Drawing.Color.FromArgb(198, 239, 206).ToArgb();
                    ranges4.Font.Color = System.Drawing.Color.FromArgb(0, 128, 0).ToArgb();
                    //加批注
                    Range range41 = sheet4.Cells[1, 1] as Range;
                    range41.AddComment("百度推广平台提示:/n请填写您新增推广单元所属的推广计划");
                    range41.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range41.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range42 = sheet4.Cells[1, 2] as Range;
                    range42.AddComment("百度推广平台提示:/n请填写您新增文字广告所属的推广单元");
                    range42.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range42.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range44 = sheet4.Cells[1, 4] as Range;
                    range44.AddComment("百度推广平台提示:/n关键词匹配模式包括:广泛、短语、精确、否定、精确否定");
                    range44.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range44.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range45 = sheet4.Cells[1, 5] as Range;
                    range45.AddComment("百度推广平台提示:/n不填写时使用推广单元的价格");
                    range45.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range45.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range46 = sheet4.Cells[1, 6] as Range;
                    range46.AddComment("百度推广平台提示:/n不填写时使用文字广告的访问URL,访问URL最大长度为1017个字符");
                    range46.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range46.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;

                    //第五个Sheet  账户 设置背景颜色和字体颜色
                    Worksheet sheet5 = (Worksheet)book.Worksheets[5];
                    Range ranges5 = sheet5.get_Range(sheet5.Cells[1, 1], sheet5.Cells[1, 2]);
                    ranges5.Interior.Color = System.Drawing.Color.FromArgb(198, 239, 206).ToArgb();
                    ranges5.Font.Color = System.Drawing.Color.FromArgb(0, 128, 0).ToArgb();
                    //加批注
                    Range range51 = sheet5.Cells[1, 1] as Range;
                    range51.AddComment("百度推广平台提示:/n不填写时默认为“不限定预算”");
                    range51.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range51.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    Range range52 = sheet5.Cells[1, 2] as Range;
                    range52.AddComment("百度推广平台提示:/n不填写时默认为“全部地域”");
                    range52.Comment.Shape.TextFrame.Characters(0, 9).Font.Bold = true;
                    range52.Comment.Shape.TextFrame.Characters(10, 500).Font.Bold = false;
                    #endregion
                    //保存
                    book.Save();
                    Kill(excel);

                    if (arrerror.Count != 0)
                    {
                        if (MessageBox.Show(this, "有错误信息,是否导出?", "世奇推广助手提示", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                        {
                            SaveFileDialog saveFileDialog = new SaveFileDialog();
                            saveFileDialog.FileName = "errorMessage";
                            saveFileDialog.Filter = "TXT文件 (*.txt)|*.txt";
                            saveFileDialog.FilterIndex = 0;
                            saveFileDialog.RestoreDirectory = true;
                            saveFileDialog.CreatePrompt = true;
                            saveFileDialog.Title = "错误信息导出";
                            saveFileDialog.ShowDialog(this);
                            if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"

                            Stream myStream;
                            myStream = saveFileDialog.OpenFile();
                            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                            foreach (string s in arrerror)
                            {
                                sw.WriteLine(s);
                            }
                            sw.Close();
                            myStream.Close();
                        }
                    }

                    lblAccount.Text = Config.UName + "导出成功";
                    btnCanCel.Text = "关闭(&C)";
                }
                catch (Exception e)
                {

                }
            }
        }

 

/// <summary>
        /// 最终的导出CSV
        /// </summary>
        void DoExportCSV(string data, string name)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.FileName = name;
                saveFileDialog.Filter = "CSV 文件 (*.csv)|*.csv";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.Title = "保存为CSV文件";
                saveFileDialog.ShowDialog(this);
                if (saveFileDialog.FileName.IndexOf(":") < 0) return; //被点了"取消"

                Stream myStream;
                myStream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                sw.WriteLine(data);
                sw.Close();
                myStream.Close();
                MessageBox.Show(this, name + "导出成功!", "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (Exception e1)
            {
                logAX.Error("最终的导出CSV DoExportCSV", e1);
                throw e1;
            }
        }


 /// <summary>
        /// 从Excel中取出数据
        /// </summary>
        /// <param name="exceltype">本机安装的Excel版本</param>
        /// <returns></returns>
        public DataTable GetTableFromExcel(int exceltype)
        {
            DataTable dt = new DataTable();
            //本机安装有Excel
            if (exceltype != 0)
            {
                DataSet ds = new DataSet();
                openFileDialog1.FileName = "";
                openFileDialog1.Filter = "Excel文件(*.xls)|*.xls|Excel文件(*.xlsx)|*.xlsx";
                openFileDialog1.FilterIndex = 0;
                openFileDialog1.Title = "选择要导入的文件";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string filepath = openFileDialog1.FileName;
                    string strCon = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", filepath);
                    if (exceltype == 2003)
                        strCon = string.Format(" Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = {0};Extended Properties=Excel 8.0", filepath);
                    try
                    {
                        //创建一个数据链接
                        using (OleDbConnection myConn = new OleDbConnection(strCon))
                        {
                            string strCom = " SELECT * FROM [Sheet1$] ";
                            myConn.Open();
                            OleDbDataAdapter myCommand = null;
                            //打开数据链接,得到一个数据集
                            try
                            {
                                myCommand = new OleDbDataAdapter(strCom, myConn);
                                //得到自己的DataSet对象
                                myCommand.Fill(ds, "[Sheet1]");
                                //关闭此数据链接
                                myConn.Close();
                            }
                            catch (OleDbException e2)
                            {
                                logAX.Error("从Excel中取出数据出错,Sheet名有误", e2);
                                MessageBox.Show(this, "Sheet名有误,请将第一个Sheet的名字改为Sheet1!", "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                        }
                    }
                    catch (Exception e1)
                    {
                        logAX.Error("从Excel中取出数据出错,文件格式或版本不对", e1);
                        MessageBox.Show(this, "文件格式或版本不对,如果本机安装的是Office2003助手只识别Excel2003,/n如果本机安装的是Office2007则Excel2003和Excel2007都可以,请核实您的文件!", "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                if (ds.Tables != null && ds.Tables.Count > 0)
                    dt = ds.Tables[0];
            }
            else//本机未安装Excel
            {
                MessageBox.Show(this, "系统检测到本机未装Excel,如果要使用此功能请安装Office软件,推荐使用Office2007!", "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            return dt;
        }

 

/// <summary>
        /// 检查本机Excel版本
        /// </summary>
        /// <returns></returns>
        public int CheckOfficeVersion()
        {
            int excelType = 0;//0表示没有 2007:安装的2007 2003:安装的2003
            string file = "";//Excel文件安装路径
            Type type = Type.GetTypeFromProgID("Excel.Application");
            if (type != null)
            {
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey akey = rk.OpenSubKey(@"SOFTWARE//Microsoft//Office//11.0//Excel//InstallRoot//");//Office2003
                RegistryKey akeytwo = rk.OpenSubKey(@"SOFTWARE//Microsoft//Office//12.0//Excel//InstallRoot//");//Office2007

                if (akey != null)
                {
                    file = akey.GetValue("Path").ToString();
                    if (File.Exists(file + "Excel.exe"))
                        excelType = 2003;
                }
                if (akeytwo != null)
                {
                    file = akeytwo.GetValue("Path").ToString();
                    if (File.Exists(file + "Excel.exe"))
                        excelType = 2007;
                }
            }
            ProcessStartInfo info = new ProcessStartInfo(file + "Excel.exe");
            return excelType;
        }

 

if (MessageBox.Show(this, "账户导入后将会用导入的数据替换助手中的数据,是否还要继续?", "世奇推广助手提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation) == DialogResult.OK)
            {
                DataTable dt = new DataTable();//存储文件中的内容
                openFileDialog1.FileName = "";
                openFileDialog1.Filter = "CSV文件(*.csv)|*.CSV";
                openFileDialog1.FilterIndex = 0;
                openFileDialog1.Title = "选择要导入的文件";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    string filepath = openFileDialog1.FileName;
                    StreamReader sr = new StreamReader(filepath, System.Text.Encoding.GetEncoding("GB2312"));
                    string readText;//读取的每一行数据
                    string[] splitStr = null;//每一列的值
                    int i = 0;
                    while (!sr.EndOfStream)//StreamReader.Peek()返回下一个可用字符,但不使用它  
                    {
                        readText = sr.ReadLine();//读取下一行
                        if (readText != "")
                        {
                            splitStr = readText.Split(',');//将每一行数据用逗号分隔开
                            if (i == 0)//第一次读的是头
                            {
                                string message = CheckCSVFile(splitStr);//检查数据是否合格
                                if (message != "")
                                {
                                    MessageBox.Show(this, message, "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                                else
                                {
                                    foreach (string str in splitStr)
                                    {
                                        dt.Columns.Add(str);
                                    }
                                }
                            }
                            else//读取数据行
                            {
                                //用递归方式将分隔好的数据还原成需要的数据
                                ArrayList arr = new ArrayList();
                                for (int a = 0; a < splitStr.Length; )//以下判断用于处理逗号在头或在尾的情况
                                {
                                    if (a + 1 < splitStr.Length)
                                    {
                                        if (splitStr[a + 1] != "/"")
                                        {
                                            arr.Add(splitStr[a]);
                                            a++;
                                        }
                                        else
                                        {
                                            if (splitStr[a].Contains("/"") && splitStr[a].LastIndexOf("/"") == splitStr[a].Length - 1)
                                            {
                                                arr.Add(splitStr[a]);
                                                arr.Add(splitStr[a + 1] + "," + splitStr[a + 2]);
                                                a += 3;
                                            }
                                            else
                                            {
                                                arr.Add(splitStr[a] + "," + splitStr[a + 1]);
                                                if (splitStr[a + 2] == "/"")
                                                {
                                                    arr.Add(splitStr[a + 2] + "," + splitStr[a + 3]);
                                                    a += 4;
                                                }
                                                else
                                                {
                                                    arr.Add(splitStr[a + 2]);
                                                    a += 3;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        arr.Add(splitStr[a]);
                                        a++;
                                    }
                                }
                                while (arr.Count > dt.Columns.Count)
                                {
                                    arr = GetRowValueByArray(arr);
                                }
                                DataRow row = dt.NewRow();
                                for (int j = 0; j < arr.Count; j++)
                                {
                                    row[j] = arr[j].ToString().Replace("/"", "");
                                }
                                dt.Rows.Add(row);
                            }
                            i++;
                        }
                    }
                    sr.Close();
                    try
                    {
                        new Accounts().ImportDataFromFile(dt);
                        MessageBox.Show(this, "数据导入成功!", "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        InitTreeView("-1");
                        InitTreeViewForMonitor("-1");
                        InitListData();
                    }
                    catch (Exception e1)
                    {
                        logAX.Error("导入CSV出错,数据格式不对", e1);
                        MessageBox.Show(this, "数据导入失败,请检查数据格式是否符合要求!", "世奇推广助手提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值