Tuesday, December 4, 2018

Excel file replace with a datatable

 #region if target file is excel then the replace method
        /// <summary>
        /// ExcelReplace
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="boolCase"></param>
        /// <returns></returns>
        private double ExcelReplace(System.Data.DataTable dt, string path, bool boolCase)
        {
            double inttotalCount = 0;
            try
            {
                Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                Workbook wb = excelApp.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);
                excelApp.DisplayAlerts = false;

                Sheets ws = wb.Worksheets;
                Worksheet worksheet = (Worksheet)ws.get_Item(1);//1st sheet in workbook

                Range range = worksheet.UsedRange;//Used cells range

                int rows = range.Rows.Count;
                int cols = range.Columns.Count;

                Range startCell = worksheet.Cells[1, 1];
                Range endCell = worksheet.Cells[rows, cols];

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    double cnt = 0;
                    //matching words count based on case sensitive

                    if (dt.Rows[i].ItemArray[0].ToString().Trim() != "")
                    {

                        if (boolCase == true)
                        {

                            //excelApp.WorksheetFunction.SumProduct(range , pattern);
                            cnt = worksheet.Evaluate(excelApp.WorksheetFunction.CountIf(range, dt.Rows[i].ItemArray[0].ToString().Trim()));
                            // cnt = Regex.Matches(worksheet.Range[startCell, endCell].ToString(), dt.Rows[i].ItemArray[0].ToString().Trim()).Count;
                            //worksheet.Range[startCell, endCell].Replace(pattern, dt.Rows[i].ItemArray[1].ToString());

                            //cnt = excelApp.WorksheetFunction.SumIf(range, dt.Rows[i].ItemArray[0].ToString().Trim());//Case sensitive
                            //  cnt = Regex.Matches(File.ReadAllText(txtTarget.Text),pattern).Count;
                            //cnt = excelApp.WorksheetFunction.SumProduct("(--Exact("+range , dt.Rows[i].ItemArray[0].ToString().Trim()+"))"+);//Case sensitive

                            //cnt= worksheet.Evaluate("excelApp.WorksheetFunction.SumProduct(--Exact(range, dt.Rows[i].ItemArray[0].ToString().Trim()))");
                            //cnt = excelApp.WorksheetFunction.CountIfs(range, dt.Rows[i].ItemArray[0].ToString().Trim(), " --MatchCase: boolCase"); //"*"+dt.Rows[i].ItemArray[0].ToString()+"*"

                        }
                        else
                        {
                            cnt = excelApp.WorksheetFunction.CountIf(range, dt.Rows[i].ItemArray[0].ToString().Trim()); //"*"+dt.Rows[i].ItemArray[0].ToString()+"*"
                                                                                                                        //  cnt = Regex.Matches(File.ReadAllText(txtTarget.Text), Regex.Escape(dt.Rows[i].ItemArray[0].ToString().Trim()), RegexOptions.IgnoreCase).Count;
                        }

                    }
                    if (cnt != 0)
                    {
                        try
                        {
                            //replace the words based on case sensitive
                            worksheet.Range[startCell, endCell].Replace(dt.Rows[i].ItemArray[0].ToString(), dt.Rows[i].ItemArray[1].ToString(), MatchCase: boolCase);
                            // MessageBox.Show("Replaced " + cnt + " entries from " + dt.Rows[i].ItemArray[0].ToString() + " to " + dt.Rows[i].ItemArray[1].ToString());
                            Log.WriteLog(Path.GetFileName(path) + " target file replaced with " + Path.GetFileName(txtDictionary.Text) + " : Replaced " + cnt + " entries from " + dt.Rows[i].ItemArray[0].ToString() + " to " + dt.Rows[i].ItemArray[1].ToString());
                        }
                        catch (Exception ex)
                        {
                            cnt = 0;
                            Log.WriteLog("ExcelReplace at Replace" + ex.Message);
                            MessageBox.Show(ex.Message);
                        }
                    }
                    //for total matched words in the file
                    inttotalCount = inttotalCount + cnt;
                }
                wb.Close(true);
                excelApp.Quit();
            }
            catch (Exception ex)
            {
                Log.WriteLog("ExcelReplace" + ex.Message);
                MessageBox.Show(ex.Message);
            }
            if (inttotalCount == 0)
            {
                File.Delete(path);
            }

            return inttotalCount;
        }

        #endregion

No comments:

Post a Comment