Advertisement
tic

Untitled

tic
Oct 24th, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 15.88 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Threading;
  7. using System.Threading;
  8.  
  9. using Excel = Microsoft.Office.Interop.Excel;
  10. using Word = Microsoft.Office.Interop.Word;
  11. using System.IO;
  12. using System.Windows.Forms;
  13. using System.Text.RegularExpressions;
  14. using System.Diagnostics;
  15.  
  16. namespace PSIP_Letters
  17. {
  18.     class Model
  19.     {
  20.         private static ViewModel _vm;
  21.         public Model(ViewModel vm)
  22.         {
  23.             _vm = vm;
  24.         }
  25.  
  26.         private string InputPath;
  27.         private string TemplatePath;
  28.         private string OutputPath;
  29.  
  30.         public void InputSelect()
  31.         {
  32.             string path = FileSelect("Excel Documents (*.xlsx)|*.xlsx|All files (*.*)|*.*");
  33.             if (path != string.Empty) _vm.InputPath = path;
  34.         }
  35.  
  36.         public void TemplateSelect()
  37.         {
  38.             string path = FileSelect("Word Documents (*.docx)|*.docx|All files (*.*)|*.*");
  39.             if (path != string.Empty) _vm.TemplatePath = path;
  40.         }
  41.  
  42.         public void OutputSelect()
  43.         {
  44.             string path = PathSelect();
  45.             if (path != string.Empty) _vm.OutputPath = path;
  46.         }
  47.  
  48.         private string FileSelect(string filter)
  49.         {
  50.             var dlg = new OpenFileDialog();
  51.             dlg.Filter = filter;
  52.             System.Windows.Forms.DialogResult result = dlg.ShowDialog();
  53.             return (result == System.Windows.Forms.DialogResult.OK) ? dlg.FileName : string.Empty;
  54.         }
  55.  
  56.         private string PathSelect()
  57.         {
  58.             var dlg = new FolderBrowserDialog();
  59.             dlg.ShowNewFolderButton = true;
  60.             System.Windows.Forms.DialogResult result = dlg.ShowDialog();
  61.             return (result == System.Windows.Forms.DialogResult.OK) ? dlg.SelectedPath : string.Empty;
  62.         }
  63.  
  64.         public void Go()
  65.         {
  66.             InputPath = _vm.InputPath;
  67.             TemplatePath = _vm.TemplatePath;
  68.             OutputPath = _vm.OutputPath;
  69.  
  70.             _vm.ErrorList = "Initializing...";
  71.             _vm.Progress = 0;
  72.  
  73.             var t1 = new Task(() =>
  74.                 {
  75.                     try
  76.                     {
  77.                         #if !DEBUG
  78.                             Process[] processes = Process.GetProcessesByName("WINWORD");
  79.                             if (processes.Length > 0)
  80.                                 throw new Exception("Error! All instances of Microsoft Word must be closed before running.");
  81.                         #endif
  82.  
  83.                         System.Array values = ReadInput();
  84.                         List<List<object>> valuesSorted = SortInput(values);
  85.                         WordOutput(valuesSorted);
  86.  
  87.                         _vm.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
  88.                         {
  89.                             _vm.ErrorList = "Complete!";
  90.                         }));
  91.                     }
  92.                     catch (Exception err)
  93.                     {
  94.                         _vm.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
  95.                         {
  96.                             _vm.ErrorList = "Error! " + err.Message;
  97.                         }));
  98.                     }
  99.                 });
  100.             t1.Start();
  101.         }
  102.  
  103.         private void WordReplace(string findText, string replaceText, Word.Application application)
  104.         {
  105.             Word.Find findObject = application.Selection.Find;
  106.             findObject.ClearFormatting();
  107.  
  108.             findObject.Text = findText;
  109.             findObject.Replacement.ClearFormatting();
  110.             findObject.Replacement.Text = replaceText;
  111.  
  112.             object m = Type.Missing;
  113.             object replaceAll = Word.WdReplace.wdReplaceAll;
  114.             findObject.Execute(ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref replaceAll, ref m, ref m, ref m, ref m);
  115.         }
  116.  
  117.         private void WordOutput(List<List<object>> values)
  118.         {
  119.             object m = Type.Missing;
  120.             OutputPath = (OutputPath.LastIndexOf('\\') == OutputPath.Length - 1) ? OutputPath : OutputPath + "\\";
  121.             OutputPath = OutputPath.Trim();
  122.             if (!Directory.Exists(OutputPath)) Directory.CreateDirectory(OutputPath);
  123.  
  124.             string Date = DateTime.Now.ToString("MMM dd, yyyy");
  125.  
  126.             Word.Application application = new Word.Application();
  127.             Word.Document document = application.Documents.Open(TemplatePath);
  128.  
  129.             object FileFormat = Word.WdSaveFormat.wdFormatXMLDocument;
  130.  
  131.             List<string> L = new List<string>();
  132.             for (int j = 1; j <= 4; ++j)
  133.             {
  134.                 L.Add(document.Tables[1].Cell(2, j).Range.Text.TrimEnd(new char[] { '\r', '\a' }));
  135.             }
  136.  
  137.             if (document.Tables[1].Rows.Count < 2)
  138.                 throw new Exception("Error! Template file is missing a complete table");
  139.  
  140.             document.Tables[1].Rows.Last.Delete();
  141.  
  142.             double personTotal = 0;
  143.             double doubleOut;
  144.             for (int i = 0; i < values.Count; ++i)
  145.             {
  146.                 string Employee_Name = (values[i][0] == null) ? string.Empty : values[i][0].ToString().Trim();
  147.                 string Employee_ID = (values[i][1] == null) ? string.Empty : values[i][1].ToString();
  148.                 string Employee_First_Name = (values[i][2] == null) ? string.Empty : values[i][2].ToString();
  149.                 string Employee_Last_Name = (values[i][3] == null) ? string.Empty : values[i][3].ToString();
  150.                 string Payroll_Location = (values[i][4] == null) ? string.Empty : values[i][4].ToString().Trim();
  151.                 string Department = (values[i][5] == null) ? string.Empty : values[i][5].ToString();
  152.                 string Sale_and_Lot = (values[i][6] == null) ? string.Empty : values[i][6].ToString();
  153.                 string Stock_RL_MSS = (values[i][7] == null) ? string.Empty : values[i][7].ToString();
  154.                 string Item_Description = (values[i][8] == null) ? string.Empty : values[i][8].ToString();
  155.                 string Sale_Date = (values[i][9] == null) ? string.Empty : DateTime.Parse(values[i][9].ToString()).ToString("MM/dd/yy");
  156.                 string Business_Unit = (values[i][10] == null) ? string.Empty : values[i][10].ToString();
  157.                 string Charge_Site = (values[i][11] == null) ? string.Empty : values[i][11].ToString();
  158.                 string Transaction_Currency_Code = (values[i][12] == null) ? string.Empty : values[i][12].ToString();
  159.                 string Transaction_Currency = (values[i][13] == null) ? string.Empty : values[i][13].ToString();
  160.                 string Purchase_Price = (values[i][14] == null) ? string.Empty : values[i][14].ToString();
  161.                 string Eligible_Percent = (values[i][15] == null) ? string.Empty : values[i][15].ToString();
  162.                 string Flat_Fee = (values[i][16] == null) ? string.Empty : values[i][16].ToString();
  163.                 string Transaction_Amount = (values[i][17] == null) ? string.Empty : values[i][17].ToString();
  164.                 string Payment_Currency_Code = (values[i][18] == null) ? string.Empty : values[i][18].ToString();
  165.                 string Payment_Currency = (values[i][19] == null) ? string.Empty : values[i][19].ToString();
  166.                 string Payment_Amount = (values[i][20] == null) ? string.Empty : values[i][20].ToString();
  167.  
  168.                 if (!Directory.Exists(OutputPath + Payroll_Location)) Directory.CreateDirectory(OutputPath + Payroll_Location);
  169.                 if (File.Exists(OutputPath + Payroll_Location + "\\" + Employee_Name + @".docx"))
  170.                 {
  171.                     try
  172.                     {
  173.                         File.Delete(OutputPath + Payroll_Location + "\\" + Employee_Name + @".docx");
  174.                     }
  175.                     catch (Exception err)
  176.                     {
  177.                         throw new Exception("Error! Could not overwrite employee " + Employee_Name);
  178.                     }
  179.                 }
  180.  
  181.                 List<string> LNew = new List<string>(L);
  182.                 bool flatFee = false;
  183.                 if (double.TryParse(Eligible_Percent, out doubleOut))
  184.                 {
  185.                     Eligible_Percent = Math.Round(doubleOut * 100, 2).ToString("F2") + "%";
  186.                     if (double.TryParse(Transaction_Amount, out doubleOut)) Transaction_Amount = Math.Round(doubleOut).ToString("#,##");
  187.                     flatFee = false;
  188.                 }
  189.                 else
  190.                 {
  191.                     if (double.TryParse(Flat_Fee, out doubleOut))
  192.                         Transaction_Amount = Math.Round(doubleOut).ToString("#,##");
  193.                     else
  194.                         throw new Exception(Employee_Name + " - Flat fee is not a number");
  195.                     flatFee = true;
  196.                 }
  197.  
  198.                 if (double.TryParse(Payment_Amount, out doubleOut))
  199.                     Payment_Amount = Math.Round(doubleOut).ToString("#,##");
  200.                 else
  201.                     throw new Exception(Employee_Name + " - Payment amount is not a number");
  202.                 personTotal += doubleOut;
  203.  
  204.                 document.Tables[1].Rows.Add();
  205.                 int count = document.Tables[1].Columns.Last.Cells.Count;
  206.  
  207.                 for (int j = 1; j <= 4; ++j)
  208.                 {
  209.                     if (j == 3)
  210.                     {
  211.                         Regex r = new Regex(@"\[IF_FLAT\]\r*(?<flatYes>.*?)\r*\[ELSE\]\r*(?<flatNo>.*?)\r*\[END_IF\]\r*", RegexOptions.Singleline);
  212.                         string replace = (flatFee) ? "flatYes" : "flatNo";
  213.                         LNew[j - 1] = r.Replace(LNew[j - 1], "${" + replace + "}");
  214.                     }
  215.  
  216.                     document.Tables[1].Cell(count, j).Range.Text = LNew[j - 1]
  217.                         .Replace("<SALE_DATE>", Sale_Date)
  218.                         .Replace("<ITEM_DESCRIPTION>", Item_Description)
  219.                         .Replace("<PERCENTAGE>", Eligible_Percent)
  220.                         .Replace("<CURRENCY>", Transaction_Currency)
  221.                         .Replace("<PAYMENT>", Transaction_Amount)
  222.                         .Replace("<CONVERTED_CURRENCY>", Payment_Currency)
  223.                         .Replace("<CONVERTED_PAYMENT>", Payment_Amount);
  224.  
  225.                     document.Tables[1].Cell(count, j).Range.Bold = 0;
  226.                     document.Tables[1].Cell(count, j).Range.Italic = 0;
  227.                 }
  228.  
  229.                 if (i == values.Count -1 || Employee_Name != values[i + 1][0].ToString())
  230.                 {
  231.                     WordReplace("<DATE>", Date, application);
  232.                     WordReplace("<FULL_NAME>", Employee_Name, application);
  233.                     WordReplace("<LAST_NAME>", Employee_Last_Name, application);
  234.                     WordReplace("<DEPARTMENT>", Department, application);
  235.                     WordReplace("<PAYROLL_LOCATION>", Payroll_Location, application);
  236.                     WordReplace("<FIRST_NAME>", Employee_First_Name, application);
  237.                     WordReplace("<TOTAL_PAYMENT>", Math.Round(personTotal).ToString("#,##"), application);
  238.                     WordReplace("<CONVERTED_CURRENCY>", Payment_Currency, application);
  239.  
  240.                     personTotal = 0;
  241.  
  242.                     Word.Range range1 = document.Content;
  243.                     Word.Find find1 = range1.Find;
  244.                     find1.Text = "<NEW_PAGE>";
  245.                     find1.ClearFormatting();
  246.                     find1.Replacement.ClearFormatting();
  247.                     find1.Replacement.Text = string.Empty;
  248.  
  249.                     range1.Find.Execute(ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m);
  250.                     var pStart = range1.get_Information(Word.WdInformation.wdActiveEndPageNumber);
  251.  
  252.                     Word.Range range2 = document.Content;
  253.                     Word.Find find2 = range2.Find;
  254.                     find2.Text = "</NEW_PAGE>";
  255.                     find2.ClearFormatting();
  256.                     find2.Replacement.ClearFormatting();
  257.                     find2.Replacement.Text = string.Empty;
  258.  
  259.                     range2.Find.Execute(ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m);
  260.                     var pEnd = range2.get_Information(Word.WdInformation.wdActiveEndPageNumber);
  261.  
  262.                     if (pStart != pEnd)
  263.                     {
  264.                         range1.Select();
  265.                         application.Selection.InsertBreak(Word.WdBreakType.wdPageBreak);
  266.                     }
  267.  
  268.                     object replaceAll = Word.WdReplace.wdReplaceAll;
  269.                     range1.Find.Execute(ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref replaceAll, ref m, ref m, ref m, ref m);
  270.                     range2.Find.Execute(ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref replaceAll, ref m, ref m, ref m, ref m);
  271.  
  272.                     string fullOutputPath = OutputPath + Payroll_Location + "\\" + Employee_Name + @".docx";
  273.                     document.SaveAs2(fullOutputPath,
  274.                         ref FileFormat,
  275.                         ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m, ref m);
  276.  
  277.                     _vm.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>
  278.                         {
  279.                             _vm.ErrorList = Payroll_Location + "-" + Employee_Name;
  280.                             _vm.Progress = (double)Math.Round((double)((decimal)i / (decimal)values.Count) * 100);
  281.                         }));
  282.  
  283.                     document.Close(false, ref m, ref m);
  284.                     document = application.Documents.Open(TemplatePath);
  285.                     document.Tables[1].Rows.Last.Delete();
  286.                 }
  287.             }
  288.             document.Close(false, ref m, ref m);
  289.             application.Quit();
  290.         }
  291.  
  292.         private System.Array ReadInput()
  293.         {
  294.             Excel.Application xlApp = new Excel.Application();
  295.             Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(InputPath, 0, false, 5, false, "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
  296.             Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlApp.Worksheets["Report"];
  297.  
  298.             string name = string.Empty;
  299.             int y = 4;
  300.             do
  301.             {
  302.                 name = xlWorkSheet.Cells[y++, 2].FormulaR1C1;
  303.             }
  304.             while (name != string.Empty);
  305.             y -= 2;
  306.  
  307.             Excel.Range range = xlWorkSheet.get_Range("B4", "V" + y.ToString());
  308.             System.Array values = (System.Array)range.Cells.Value;
  309.  
  310.             xlWorkbook.Close(false, false, false);
  311.             xlApp.Quit();
  312.  
  313.             return values;
  314.         }
  315.  
  316.         private List<List<object>> SortInput(System.Array values)
  317.         {
  318.             List<object> employeeIDs = new List<object>();
  319.  
  320.             for (int i = values.GetLowerBound(0); i <= values.GetUpperBound(0); ++i)
  321.             {
  322.                 employeeIDs.Add(values.GetValue(i, 2));
  323.             }
  324.             employeeIDs = employeeIDs.Distinct().ToList();
  325.  
  326.  
  327.             List<List<object>> L = new List<List<object>>();
  328.  
  329.             for (int i = 0; i < employeeIDs.Count; ++i)
  330.             {
  331.                 for (int j = values.GetLowerBound(0); j <= values.GetUpperBound(0); ++j)
  332.                 {
  333.                     if (object.Equals(values.GetValue(j, 2), employeeIDs[i]))
  334.                     {
  335.                         List<object> l = new List<object>();
  336.  
  337.                         for (int x = values.GetLowerBound(1); x <= values.GetUpperBound(1); ++x)
  338.                         {
  339.                             l.Add(values.GetValue(j, x));
  340.                         }
  341.                         L.Add(l);
  342.                     }
  343.                 }
  344.             }
  345.             return L;
  346.         }
  347.     }
  348. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement