Esempio n. 1
0
        public void Dispose()
        {
            GC.SuppressFinalize(this);

            // communicate with COM in a separate thread
            Task.Run(() =>
            {
                try
                {
                    //_wordApp?.Documents.Close(false);
                    _wordApp?.Quit(false);
                    _wordApp = null;

                    _excelApp?.Workbooks.Close();
                    _excelApp?.Quit();
                    _excelApp = null;

                    _powerpointApp?.Quit();
                    _powerpointApp = null;
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    Debug.WriteLine(e.StackTrace);
                }
            })
            .Wait();
        }
Esempio n. 2
0
        private static string GetTextFromWord(Word.Application WordApp, string file)
        {
            //converts document to string
            StringBuilder text     = new StringBuilder();
            object        miss     = System.Reflection.Missing.Value;
            object        path     = file;
            object        readOnly = true;

            Microsoft.Office.Interop.Word.Document docs = WordApp.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
            string WordText = docs.Range().Text;

            docs.Application.Quit();
            return(WordText);
        }
Esempio n. 3
0
        private void LoadApplication()
        {
            var succeeded = false;

            // communicate with COM in a separate thread
            Task.Run(() =>
            {
                try
                {
                    switch (FileType)
                    {
                    case FileTypeEnum.Word:
                        _wordApp = new Microsoft.Office.Interop.Word.Application();
                        _wordApp.Documents.Add(_path);
                        succeeded = true;
                        break;

                    case FileTypeEnum.Excel:
                        _excelApp = new Application();
                        _excelApp.Workbooks.Add(_path);
                        succeeded = true;
                        break;

                    case FileTypeEnum.PowerPoint:
                        _powerpointApp = new Microsoft.Office.Interop.PowerPoint.Application();
                        _powerpointApp.Presentations.Open(_path);
                        succeeded = true;
                        break;

                    default:
                        throw new NotSupportedException($"{_path} is not supported.");
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    Debug.WriteLine(e.StackTrace);
                }
            })
            .Wait();

            if (!succeeded)
            {
                Dispose();
            }
        }
Esempio n. 4
0
        private void button1_Click(object sender, EventArgs e)
        {
            KillProcess("excel");
            OpenFileDialog oFile = new OpenFileDialog();

            oFile.Filter = @"Word文件(*.doc,*.docx)|*.doc;*.docx";
            if (oFile.ShowDialog() == DialogResult.OK)
            {
                object oFileName = oFile.FileName;
                //object oFileName = @"D:\图片\test.docx";
                object oReadOnly = true;
                object oMissing  = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word._Document   oDoc;
                Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();
                oWord.Visible = true;//只是为了方便观察
                oDoc          = oWord.Documents.Open(ref oFileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                     ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
                                                     ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                string tableMessage = "";
                string tmp;
                string path = AppDomain.CurrentDomain.BaseDirectory + "生成的excel文件";
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string oExcelName = path + "\\" + "生成的excel" + ".xlsx";
                object oRead      = false;
                object oMiss      = System.Reflection.Missing.Value;
                var    oExcel     = new Microsoft.Office.Interop.Excel.Application();
                //Microsoft.Office.Interop.Excel.Workbook xBook = oExcel.Workbooks.Open(oExcelName, oMiss, oRead, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss, oMiss,oMiss, oMiss, oMiss);
                Microsoft.Office.Interop.Excel.Workbook xBook = oExcel.Workbooks.Add(Type.Missing);

                Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xBook.ActiveSheet;
                //Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets.get_Item(oDoc.Tables.Count);
                // Microsoft.Office.Interop.Excel._Worksheet xSt1 = (Microsoft.Office.Interop.Excel._Worksheet)xBook.Sheets.Add(Missing.Value, ws, Missing.Value, Missing.Value);
                if (oDoc.Tables.Count <= 0)
                {
                    return;
                }
                if (oDoc.Tables.Count > 1)
                {
                    ws = xBook.Sheets.Add(Missing.Value, ws, oDoc.Tables.Count - 1, Missing.Value);
                }

                Microsoft.Office.Interop.Excel.Sheets shs = oExcel.Sheets;
                for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++)
                {
                    if (oDoc.Tables.Count <= 1)
                    {
                    }
                    else
                    {
                        ws = xBook.Sheets[tablePos];;
                    }
                    Microsoft.Office.Interop.Word.Table nowTable = oDoc.Tables[tablePos];
                    int n = oDoc.Tables[tablePos].Rows.Count;
                    for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
                    {
                        for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
                        {
                            Microsoft.Office.Interop.Excel.Range rang = (Microsoft.Office.Interop.Excel.Range)ws.Cells[rowPos, columPos];
                            //if ((bool)rang.MergeCells==false)
                            //{
                            tableMessage = nowTable.Cell(rowPos, columPos).Range.Text.Trim();
                            tmp          = tableMessage.Replace("\r\a", "");
                            ws.Cells[rowPos, columPos] = tmp;
                            //}
                        }
                    }
                }
                ws.SaveAs(oExcelName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                MessageBox.Show(oExcelName + @"已成功生成" + oDoc.Tables.Count.ToString() + @"个表格");
                oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
                oExcel.Quit();
            }
        }
Esempio n. 5
0
        private void button5_Click(object sender, EventArgs e)
        {
            object missing = Type.Missing;


            Object Pa = textBox2.Text;                         // Путь к шаблону

            Word.Application wordApp = new Word.Application(); // Создаём объект приложения


            wordApp.Documents.Open(ref Pa, ref missing, true, ref missing, ref missing,
                                   ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing, ref missing, ref missing);

            Word.Document document = wordApp.ActiveDocument;

            int       countTable = document.Tables.Count;
            var       someList   = new List <string>();
            DataTable dataTable  = new DataTable();

            progressBar2.Value = 0;

            for (int y = 1; y <= countTable; y++)
            {
                Word.Table table = document.Tables[y];

                if (table.Rows.Count > 0 && table.Columns.Count > 0)
                {
                    for (int i = 0; i < table.Columns.Count && someList.Count != table.Columns.Count; i++)
                    {
                        dataTable.Columns.Add();
                        someList.Add(table.Cell(1, i + 1).Range.Text.Trim('a', 'r', 'n', 't').Replace("\r", " ").Replace("\a", "").Replace("\t", ""));
                    }


                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        progressBar2.Maximum = (countTable) * table.Columns.Count;
                        progressBar2.Value++;
                    }
                    for (int i = 0; i < table.Rows.Count - 1; i++)
                    {
                        string[] row = new string[table.Columns.Count];
                        for (int j = 0; j < table.Columns.Count; j++)
                        {
                            row[j] = table.Cell(i + 2, j + 1).Range.Text.Trim('a', 'r', 'n', 't').Replace("\r", " ").Replace("\a", "").Replace("\t", "").Replace("\v", " ");
                        }



                        DateTime d;
                        string   dateConv = row[2].Replace("\a", "");
                        string   tlFio    = dateConv;
                        if (string.IsNullOrEmpty(tlFio) || tlFio == " ")
                        {
                            tlFio = "0001-01-01 00:00:00.000";
                        }
                        try
                        {
                            string[] b = tlFio.Split(new char[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
                            string   o = b[0] + "." + b[1] + "." + b[2];

                            if (DateTime.TryParse(o, out d))
                            {
                                d = Convert.ToDateTime(o);
                            }
                            else
                            {
                                o = "0001-01-01 00:00:00.000";// Если дата введена не коретно то вводиться это число 2000-01-01 00:00:00.000
                            }
                            d = Convert.ToDateTime(o);

                            row[2] = Convert.ToString(d);
                        }
                        catch
                        {
                            MessageBox.Show("данные у пользователя: " + row[1] + "неверные ");
                        }
                        dataTable.Rows.Add(row);
                    }
                }
            }

            dataGridView2.DataSource = dataTable;
            for (int i = 0; i < someList.Count; i++)
            {
                //dataGridView1.Columns.Add(someList[i], "");
                dataGridView2.Columns[i].HeaderText = someList[i];
            }



            wordApp.ActiveDocument.Close();
            wordApp.Quit();



            MessageBox.Show("Данные помещены");
        }
Esempio n. 6
0
        private void button5_Click(object sender, EventArgs e)
        {
            using (TexnikymBDEntities db = new TexnikymBDEntities())
            {
                object missing = Type.Missing;


                Object Pa = textBox2.Text;                         // Путь к шаблону

                Word.Application wordApp = new Word.Application(); // Создаём объект приложения


                wordApp.Documents.Open(ref Pa, ref missing, true, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                       ref missing, ref missing, ref missing, ref missing, ref missing);

                Word.Document document = wordApp.ActiveDocument;

                int countTable = document.Tables.Count;

                for (int y = 1; y <= countTable; y++)
                {
                    List <Студенты2> ShabloniGr = new List <Студенты2>();
                    Word.Table       table      = document.Tables[y];

                    if (table.Rows.Count > 0 && table.Columns.Count > 0)
                    {
                        for (int i = 0; i < table.Columns.Count; i++)
                        {
                            progressBar2.Maximum = (countTable) * table.Columns.Count;
                            progressBar2.Value++;
                        }
                        for (int i = 0; i < table.Rows.Count - 1; i++)
                        {
                            string[] row = new string[table.Columns.Count];
                            for (int j = 0; j < table.Columns.Count; j++)
                            {
                                row[j] = table.Cell(i + 2, j + 1).Range.Text.Trim('a', 'r', 'n', 't').Replace("\r", " ").Replace("\a", "").Replace("\t", "");
                            }



                            DateTime d;
                            string   dateConv = row[2].Replace("\a", "");
                            string   tlFio    = dateConv;
                            string[] b        = tlFio.Split(new char[] { ' ', '.', ',' }, StringSplitOptions.RemoveEmptyEntries);
                            string   o        = b[0] + "." + b[1] + "." + b[2];

                            if (DateTime.TryParse(o, out d))
                            {
                                d = Convert.ToDateTime(o);
                            }
                            else
                            {
                                o = "2000-01-01 00:00:00.000";// Если дата введена не коретно то вводиться это число 2000-01-01 00:00:00.000
                            }
                            d = Convert.ToDateTime(o);

                            ShabloniGr.Add(new Студенты2
                            {
                                ФИО              = row[1],
                                ДатаРождения     = d,
                                ПаспортныеДанные = row[3],
                                МедицинскийПолис = row[4],
                                Снилс            = row[5],
                                ИНН              = row[6]
                            });
                        }
                    }
                    db.Студенты2.AddRange(ShabloniGr);
                    db.SaveChanges();
                }

                wordApp.ActiveDocument.Close();
                wordApp.Quit();

                db.Студенты2.Load();

                dataGridView2.DataSource = db.Студенты2.Local.ToBindingList();

                MessageBox.Show("Данные помещены");
            }
        }
Esempio n. 7
0
        public static void Main(string[] args)
        {
            String        directorySearch;
            List <string> docFiles   = new List <string>();
            List <string> excelFiles = new List <string>();
            List <string> pdfFiles   = new List <string>();
            List <string> textFiles  = new List <string>();
            string        Print      = "";

            //Console Enter
            Console.WriteLine("Enter File Path");
            directorySearch = Console.ReadLine();
            while (!Directory.Exists(directorySearch))
            {
                Console.WriteLine("Enter a VALID File Path");
                directorySearch = Console.ReadLine();
            }
            Console.WriteLine("***************************************");

            // doc files
            docFiles = DirSearchWord(directorySearch);
            List <string> DirSearchWord(string ds)
            {
                try
                {
                    //Searches all directories and checks their file extentions
                    var files = Directory.EnumerateFiles(ds, "*.*")
                                .Where(s => s.EndsWith(".doc", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".docx", StringComparison.OrdinalIgnoreCase));

                    foreach (string file in files)
                    {
                        //opens word app here so it can be easily disposed
                        Word.Application app = new Word.Application();
                        try
                        {
                            //calls get text word and find text doc which do all the checks
                            FindTextDoc(GetTextFromWord(app, file), file);

                            //Prints the file that is opened (doesnt for any files that are: corrupted, acces denied or any other erros
                            Console.WriteLine(file);
                        }
                        catch (System.Runtime.InteropServices.COMException)
                        {
                            corrupted.Add(file);
                        }
                        app.Quit();
                    }
                    foreach (string directory in Directory.GetDirectories(ds))
                    {
                        //goes into subdirectores/folders
                        docFiles.AddRange(DirSearchWord(directory));
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    accessDenied.Add(ds);
                }
                catch (System.Exception)
                {
                    generalErrors.Add(ds);
                }
                return(docFiles);
            }

            //Excel Documents
            excelFiles = DirSearchExcel(directorySearch);

            List <string> DirSearchExcel(string ds)
            {
                try
                {
                    //Searches all directories and checks their file extentions
                    var files = Directory.EnumerateFiles(ds, "*.*")
                                .Where(s => s.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".xlsm", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".xltx", StringComparison.OrdinalIgnoreCase) ||
                                       s.EndsWith(".xltm", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".csv", StringComparison.OrdinalIgnoreCase));
                    foreach (string file in files)
                    {
                        try
                        { //opens word app here so it can be easily disposed
                            Microsoft.Office.Interop.Excel.Application oXL = new Microsoft.Office.Interop.Excel.Application();

                            //? is used for any charcter in excel
                            FindExcel(oXL, file);

                            Console.WriteLine(file);
                        }
                        catch (System.Runtime.InteropServices.COMException)
                        {
                            corrupted.Add(file);
                        }
                    }
                    foreach (string directory in Directory.GetDirectories(ds))
                    {
                        //goes into subdirectores/folders
                        excelFiles.AddRange(DirSearchExcel(directory));
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    accessDenied.Add(ds);
                }
                catch (System.Exception)
                {
                    generalErrors.Add(ds);
                }
                return(excelFiles);
            }

            //pdf documents
            pdfFiles = DirSearchPDF(directorySearch);
            string     currentPdfText;
            ExtractPDF currPdf;

            List <string> DirSearchPDF(string ds)
            {
                try
                { //Searches all directories and checks their file extentions
                    var files = Directory.EnumerateFiles(ds, "*.*")
                                .Where(s => s.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase));
                    foreach (string file in files)
                    {
                        try
                        {
                            currPdf        = new ExtractPDF(file);
                            currentPdfText = currPdf.extract();
                            if (currentPdfText == "Filename is incorrect or cannot be found.")
                            {
                                Console.WriteLine("Couldn't read {0}.", file);
                            }
                            else
                            {
                                //finds text in pdf after extracted from pdf
                                FindTextDoc(currentPdfText, file);
                                Console.WriteLine(file);
                            }
                        }
                        catch (System.Runtime.InteropServices.COMException)
                        {
                            corrupted.Add(file);
                        }
                    }
                    foreach (string directory in Directory.GetDirectories(ds))
                    {
                        //goes into subdirectores/folders
                        pdfFiles.AddRange(DirSearchPDF(directory));
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    accessDenied.Add(ds);
                }
                catch (System.Exception)
                {
                    generalErrors.Add(ds);
                }
                return(pdfFiles);
            }

            textFiles = DirSearchTextFiles(directorySearch);
            List <string> DirSearchTextFiles(string ds)
            {
                try
                {
                    //Searches all directories and checks their file extentions
                    var files = Directory.EnumerateFiles(ds, "*.*")
                                .Where(s => s.EndsWith(".txt", StringComparison.OrdinalIgnoreCase));

                    foreach (string file in files)
                    {
                        try
                        {
                            //extracts all the text from a textfile into a string which we then parse through
                            string readText = File.ReadAllText(file);
                            FindTextDoc(readText, file);
                            Console.WriteLine(file);
                        }
                        catch (System.Runtime.InteropServices.COMException)
                        {
                            corrupted.Add(file);
                        }
                    }
                    foreach (string directory in Directory.GetDirectories(ds))
                    {
                        //goes into subdirectores/folders
                        textFiles.AddRange(DirSearchTextFiles(directory));
                    }
                }
                catch (System.UnauthorizedAccessException)
                {
                    accessDenied.Add(ds);
                }
                catch (System.Exception)
                {
                    generalErrors.Add(ds);
                }
                return(excelFiles);
            }

            Console.WriteLine("***************************************");
            accessDenied = accessDenied.Distinct().ToList();
            Console.WriteLine("Files That Contain SSN Formating: ");
            Console.WriteLine("");
            filesThatConstainSSN.ForEach(Console.WriteLine);

            SaveFileDialog saveFileDialog1 = new SaveFileDialog
            {
                InitialDirectory = @"*\Documents",                                                                 //intial location for save
                Filter           = "Microsoft Word Documents|*.DOC | txt files (*.txt)|*.txt|All files (*.*)|*.*", // or just "txt files (*.txt)|*.txt" if you only want to save text files
                FilterIndex      = 2,
                RestoreDirectory = true
            };

            //Writes to a textfile with headers
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Print = saveFileDialog1.FileName;
                StreamWriter writer = new StreamWriter(saveFileDialog1.FileName);
                using (writer)
                {
                    writer.WriteLine("****Files that contain SSN Numbers****");
                    foreach (String s in filesThatConstainSSN)
                    {
                        writer.WriteLine(s);
                    }
                    writer.WriteLine();
                    writer.WriteLine();
                    writer.WriteLine("********Unkown/General Errors*********");
                    foreach (String ge in generalErrors)
                    {
                        writer.WriteLine(ge);
                    }
                    writer.WriteLine();
                    writer.WriteLine("***********Corrupted File*************");
                    foreach (String c in corrupted)
                    {
                        writer.WriteLine(c);
                    }
                    writer.WriteLine();
                    writer.WriteLine("***********Acces Was Denied***********");
                    foreach (String ad in accessDenied)
                    {
                        writer.WriteLine(ad);
                    }
                    writer.Close();
                }
            }
            try
            {
                //tries to opne save document if it wasnt saved we catch the excepion
                Process.Start(Print);
            }
            catch
            {
                Console.WriteLine("File Was Not Saved!");
                Console.ReadLine();
            }
        }