Пример #1
1
        public void ExportToExcel(DataGridView grid,string r_id,string time)
        {
            ApplicationClass Excel = new ApplicationClass();
            XlReferenceStyle RefStyle = Excel.ReferenceStyle;
            Excel.Visible = true;
            Workbook wb = null;
            String TemplatePath = System.Windows.Forms.Application.StartupPath + @"\Отчет"+r_id+".xlt";
            try
            {
                wb = Excel.Workbooks.Add(TemplatePath); // !!!
            }
            catch (System.Exception ex)
            {
                throw new Exception("Не удалось загрузить шаблон для экспорта " + TemplatePath + "\n" + ex.Message);
            }
            Worksheet ws = wb.Worksheets.get_Item(1) as Worksheet;

            ws.Cells[20, 3] = time;

            for (int j = 0; j < grid.Columns.Count; ++j)
            {
                //(ws.Cells[1+20, j + 1+2] as Range).Value2 = grid.Columns[j].HeaderText;
                for (int i = 0; i < grid.Rows.Count; ++i)
                {
                    object Val = grid.Rows[i].Cells[j].Value;
                    if (Val != null)
                        (ws.Cells[i + 2+20, j + 1+2] as Range).Value2 = Val.ToString();
                }
            }
               // ws.Columns.EntireColumn.AutoFit();
            Excel.ReferenceStyle = RefStyle;
            ReleaseExcel(Excel as Object);
        }
Пример #2
0
        public static List<string> GetSheetNames(string fileName)
        {
            ApplicationClass excelapp = new ApplicationClass();
            RecentFile re = excelapp.RecentFiles.Add(fileName);// nhan ve file vua chon de xu ly
            List<string> lstSheet = new List<string>();
            try
            {
                excelapp.Visible = false;
                Workbook excelWorkbook = re.Open();// mở ra và có thể truy xuất các sheet
                if (excelWorkbook.Sheets.Count > 0)
                {
                    Worksheet excelWorkSheet;
                    for (int i = 1; i <= excelWorkbook.Sheets.Count; i++)
                    {
                        excelWorkSheet = (Worksheet)excelWorkbook.Sheets[i];
                        lstSheet.Add(excelWorkSheet.Name);
                    }
                    excelWorkSheet = null;
                }
                excelWorkbook = null;
                re.Application.Quit();
                excelapp.Quit();// thoat khoi chuong trinh excel.exe trong he thong

            }
            catch (Exception) { }
            return lstSheet;
        }
Пример #3
0
        public static void SaveExcelFile(string fileName, string tempFileName,string[,] contents, int startColumn, int startRow)
        {
            try
            {
                excelApp = new ApplicationClass();
                Workbooks myWorkBooks = excelApp.Workbooks;
                myWorkBooks.Open(tempFileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                Sheets sheets = excelApp.Sheets;
                mySheet1 = (Worksheet)sheets[1];
                mySheet1.Activate();

                //写入测试信息
                Range range1 = mySheet1.get_Range(mySheet1.Cells[startRow, startColumn], mySheet1.Cells[contents.GetLength(0)+startRow-1,contents.GetLength(1)+startColumn-1]);
                range1.Value2 = contents;
                mySheet1.SaveAs(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                myWorkBooks.Close();
                excelApp.Quit();
                excelApp = null;
            }
            catch (Exception ee)
            {

                throw ee;
            }
        }
Пример #4
0
 private void x()
 {
     Excel.Application app = new ApplicationClass();
     try
     {
         //app.ActivePrinter = "Acrobat Distiller";
         Workbooks workBooks = app.Workbooks;
         Workbook workBook = (Workbook )workBooks.GetType().InvokeMember("Open",BindingFlags.InvokeMethod,null,workBooks,new object[]{@"C:\Documents and Settings\raghunandanr\Desktop\Template Format for PDF Transcription1.xls"});
         workBook.PrintOut(1,Type.Missing,1,false,"Acrobat Distiller",true,true,@"C:\Documents and Settings\raghunandanr\Desktop\Template Format for PDF Transcription1.ps");
         workBook.Close(false,Type.Missing,Type.Missing);
         PdfDistiller dist = new PdfDistillerClass();
         //dist.bSpoolJobs = 1;
         dist.bShowWindow = 0;
         dist.OnJobFail += new _PdfEvents_OnJobFailEventHandler(Fail);
         dist.FileToPDF(@"C:\Documents and Settings\raghunandanr\Desktop\Template Format for PDF Transcription1.ps",null,null);
         Marshal.ReleaseComObject(dist);
         dist=null;
     }
     catch(Exception ex){Response.Write(ex.Message);}
     finally
     {
         app.Quit();
         Marshal.ReleaseComObject(app);
         app = null;
         GC.Collect();
         GC.WaitForPendingFinalizers();
     }
 }
Пример #5
0
        private void Bai2_Load(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Word.ApplicationClass wordApplication = new ApplicationClass();
            object o_nullobject = System.Reflection.Missing.Value;
            object o_filePath = System.IO.Directory.GetCurrentDirectory() + "\\Resources\\PhepNhan.doc";
            object o_format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
            object o_encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
            object o_endings = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;
            object o_Readonly = true;
            Microsoft.Office.Interop.Word.Document doc = wordApplication.Documents.Open(ref o_filePath,
            ref o_nullobject, ref o_Readonly, ref o_nullobject, ref o_nullobject, ref o_nullobject,
            ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject,
            ref o_nullobject, ref o_nullobject);

            doc.ActiveWindow.Selection.WholeStory();

            doc.ActiveWindow.Selection.Copy();

            IDataObject data = Clipboard.GetDataObject();

            txtLyThuyet.Text = data.GetData(DataFormats.UnicodeText).ToString();

            doc.Close(ref o_nullobject, ref o_nullobject, ref o_nullobject);
            wordApplication.Quit(ref o_nullobject, ref o_nullobject, ref o_nullobject);

            PhepTinhDAO phepTinhDAO = new PhepTinhDAO();
            PhepTinhDTO phepTinhDTO = new PhepTinhDTO();

            arrPhepTinh = phepTinhDAO.getPhepTinhNhan();
            sizeOfXML = arrPhepTinh.Count;
            phepTinhDTO = (PhepTinhDTO)arrPhepTinh[0];
            tbTemp1.Text = phepTinhDTO.SoThuNhat.ToString();
            tbTemp2.Text = phepTinhDTO.SoThuHai.ToString();
        }
Пример #6
0
        public static void WriteToNewWordFile(string path, string text)
        {
            ApplicationClass wordApp = new ApplicationClass();


            object nullobj = Missing.Value;
            object file = path;
            object fileFormat = WdSaveFormat.wdFormatHTML;
            object encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
            

            FileUtils.WriteAllText(path, text);

            var doc = wordApp.Documents.Add(ref nullobj, ref nullobj, ref nullobj, ref nullobj);

            if (text.IsNull())// If file open in first time save as word html
            {
                doc.SaveAs(ref file, ref fileFormat, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj, ref nullobj,
                    ref nullobj, ref nullobj, ref nullobj,
                    /*Encoding*/ref encoding, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
            }
            (doc as _Document).Close(ref nullobj, ref nullobj, ref nullobj);
            wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
        }
Пример #7
0
 void ConvertDocument(Guid g, string fileName)
 {
     object m = System.Reflection.Missing.Value;
     object oldFileName = (object)fileName;
     object readOnly = (object)false;
     ApplicationClass ac = null;
     try
     {
         // First, create a new Microsoft.Office.Interop.Word.ApplicationClass.
         ac = new ApplicationClass();
         // Now we open the document.
         Document doc = ac.Documents.Open(ref oldFileName, ref m, ref readOnly,
             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);
         // Create a temp file to save the HTML file to.
         string tempFileName =Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + g.ToString() + ".html";
         // Cast these items to object.  The methods we're calling
         // only take object types in their method parameters.
         object newFileName = (object)tempFileName;
         // We will be saving this file as HTML format.
         object fileType = (object)WdSaveFormat.wdFormatHTML;
         // Save the file.
         doc.SaveAs(ref newFileName, ref fileType,
             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);
     }
     finally
     {
         // Make sure we close the application class.
         if (ac != null)
             ac.Quit(ref readOnly, ref m, ref m);
     }
 }
Пример #8
0
        private void Bai1_Load(object sender, EventArgs e)
        {
            currentIndex=0;
            So5ChuSoDAO so5ChuSoDAO = new So5ChuSoDAO();
            So5ChuSoDTO so5ChuSoDTO = null;

            arrSo5ChuSo = so5ChuSoDAO.getSo5ChuSo();
            sizeOfXML = arrSo5ChuSo.Count;
            so5ChuSoDTO = (So5ChuSoDTO)arrSo5ChuSo[0];
            lbDocSo.Text = so5ChuSoDTO.Text;
            currentResult = so5ChuSoDTO.Number;

            Microsoft.Office.Interop.Word.ApplicationClass wordApplication = new ApplicationClass();
            object o_nullobject = System.Reflection.Missing.Value;
            object o_filePath = System.IO.Directory.GetCurrentDirectory() + "\\Resources\\CacSoCo5ChuSo.doc";
            object o_format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
            object o_encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
            object o_endings = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF;
            object o_Readonly = true;
            Microsoft.Office.Interop.Word.Document doc = wordApplication.Documents.Open(ref o_filePath,
            ref o_nullobject, ref o_Readonly, ref o_nullobject, ref o_nullobject, ref o_nullobject,
            ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject, ref o_nullobject,
            ref o_nullobject, ref o_nullobject);

            doc.ActiveWindow.Selection.WholeStory();

            doc.ActiveWindow.Selection.Copy();

            IDataObject data = Clipboard.GetDataObject();

            txtLyThuyet.Text = data.GetData(DataFormats.UnicodeText).ToString();

            doc.Close(ref o_nullobject, ref o_nullobject, ref o_nullobject);
            wordApplication.Quit(ref o_nullobject, ref o_nullobject, ref o_nullobject);
        }
Пример #9
0
 public static void Word2Pdf(string path, string savepath)
 {
     var word = new ApplicationClass();
     var wordType = word.GetType();
     var docs = word.Documents;
     var docsType = docs.GetType();
     var doc = (Document) docsType.InvokeMember(
         "Open",
         BindingFlags.InvokeMethod,
         null,
         docs,
         new[] {(object)path, true, true});
     var docType = doc.GetType();
     docType.InvokeMember(
         "SaveAs",
         BindingFlags.InvokeMethod,
         null,
         doc,
         new[] {(object) savepath, WdSaveFormat.wdFormatPDF});
     docType.InvokeMember(
         "Close",
         BindingFlags.InvokeMethod,
         null,
         doc,
         new object[] {WdSaveOptions.wdDoNotSaveChanges});
     wordType.InvokeMember(
         "Quit",
         BindingFlags.InvokeMethod,
         null,
         word,
         null);
 }
Пример #10
0
        private static Worksheet mySheet1; //工作簿1

        #endregion Fields

        #region Methods

        public static List<List<string>> Read(string fileName,int columnCount,int startRowIndex)
        {
            List<List<string>> textList = new List<List<string>>();
            excelApp = new ApplicationClass();
            Workbooks myWorkBooks = excelApp.Workbooks;
            myWorkBooks.Open(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
            Sheets sheets = excelApp.Sheets;
            mySheet1 = (Worksheet)sheets[1];
            int rowCount = mySheet1.UsedRange.Rows.Count;
            if (rowCount != 0)
            {
                for (int i = startRowIndex; i <= rowCount; i++)
                {
                    string name = ((Range)mySheet1.Cells[i, 2]).Text.ToString();

                    if (name != "") {
                        List<string> list = new List<string>();
                        list.Add((i-startRowIndex+1).ToString());
                        for (int j = 0; j < columnCount; j++)
                        {
                            list.Add(((Range)mySheet1.Cells[i, j + 1]).Text.ToString());
                        }
                        textList.Add(list);
                    }
                }
            }
            myWorkBooks.Close();
            excelApp.Quit();
            excelApp = null;
            return textList;
        }
Пример #11
0
 public static Workbook DataTableToWorkBook(System.Data.DataTable dt, string[] Cells)
 {
     if (dt.Columns.Count < 1)
     {
         throw new Exception("_Excel.DataTableToWorkBook 方法提供的 DataTable 参数找不到任何可用的列。");
     }
     Application application = new ApplicationClass();
     Workbook workbook = application.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
     Worksheet worksheet = (Worksheet) workbook.Worksheets[1];
     long count = dt.Rows.Count;
     long num2 = 0L;
     for (int i = 0; i < dt.Columns.Count; i++)
     {
         if (((Cells != null) && (Cells.Length > i)) && !string.IsNullOrEmpty(Cells[i]))
         {
             worksheet.Cells[1, i + 1] = Cells[i].Trim();
         }
         else
         {
             worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
         }
         Microsoft.Office.Interop.Excel.Range range1 = (Microsoft.Office.Interop.Excel.Range) worksheet.Cells[1, i + 1];
     }
     for (int j = 0; j < dt.Rows.Count; j++)
     {
         for (int k = 0; k < dt.Columns.Count; k++)
         {
             worksheet.Cells[j + 2, k + 1] = dt.Rows[j][k];
             Microsoft.Office.Interop.Excel.Range range2 = (Microsoft.Office.Interop.Excel.Range) worksheet.Cells[j + 2, k + 1];
         }
         num2 += 1L;
         float single1 = ((float) (100L * num2)) / ((float) count);
     }
     return workbook;
 }
Пример #12
0
        private void button1_Click(object sender, EventArgs e)
        {
            var from = DateTimePickerFrom.Value;
            var to = DateTimePickerTo.Value;

            if(from >= to)
            {
                MessageBox.Show("To date must be later than From date", "Error");
                return;
            }

            var fridays = new List<DateTime>();
            var saturdays = new List<DateTime>();
            for (; from <= to; from.AddDays(1))
            {
                switch (from.DayOfWeek)
                {
                    case DayOfWeek.Friday:
                        fridays.Add(from);
                        break;
                    case DayOfWeek.Saturday:
                        saturdays.Add(from);
                        break;
                }
            }

            var excel = new ApplicationClass();
        }
        public void InstrumentationCanBeAttachedToInstrumentationProviderWhenInstanceNameIsPresent()
        {
            ApplicationClass applicationObject = new ApplicationClass();
            strategy.AttachInstrumentation("InstanceName", applicationObject, instrumentationConfigurationSource, reflectionCache);

            Assert.IsTrue(((InstrumentationProvider) (applicationObject.GetInstrumentationEventProvider())).IsWired);
        }
Пример #14
0
        public Dictionary<string, List<TermContainer>> getTestSpecificationDocTOC(Document doc, ApplicationClass app)
        {
            generateTOC(doc, app);
            Range tocRange = doc.TablesOfContents[1].Range;
            string[] tocContents = delimiterTOC(tocRange.Text);

            Dictionary<string, List<TermContainer>> dict = new Dictionary<string, List<TermContainer>>();
            string chapter = "";

            foreach (string s in tocContents)
            {
                if (isLevel1(s))
                {
                    chapter = s;
                    dict.Add(s, new List<TermContainer>());
                }
                else
                {
                    if (isLevel2(s))
                    {
                        TermContainer term = new TermContainer("", s, null);
                        dict[chapter].Add(term);
                    }
                }

            }
            return dict;
        }
Пример #15
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="UnEncryptFileName">Excel原始檔名</param>
    /// <param name="EncryptFileName">Excel加密後檔名</param>
    /// <param name="OpenExcelPassword">允許開啟密碼</param>
    /// <param name="WriteExcelPassword">允許編寫密碼</param>
    public static void EncryptExcelByPassword(string UnEncryptFileName, string EncryptFileName,
        string OpenExcelPassword, string WriteExcelPassword)
    {
        ApplicationClass xApp = new ApplicationClass();
        try
        {
            Workbook xBook = xApp.Workbooks.Open(UnEncryptFileName,
          Missing.Value, Missing.Value, Missing.Value, Missing.Value,
          Missing.Value, Missing.Value, Missing.Value, Missing.Value,
          Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            if (File.Exists(EncryptFileName)) File.Delete(EncryptFileName);

            xBook.SaveAs(EncryptFileName, XlFileFormat.xlExcel12
                , OpenExcelPassword, WriteExcelPassword, Missing.Value,
              Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value,
              Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            xBook.Save();
            xBook.Close();
            xBook = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            xApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xApp);
            xApp = null;
        }
        GC.Collect();
    }
        void ConvertDocument(Guid g, string fileName)
        {
            object m = System.Reflection.Missing.Value;
            object oldFileName = (object)fileName;
            object readOnly = (object)false;
            ApplicationClass ac = null;
            System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            try
            {

                System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
                // First, create a new Microsoft.Office.Interop.Word.ApplicationClass.
                ac = new ApplicationClass();

                // Now we open the document.
                Presentation doc = ac.Presentations.Open(fileName , Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);

                // Create a temp file to save the HTML file to.
                string tempFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), g.ToString() + ".html");
                // Cast these items to object.  The methods we're calling
                // only take object types in their method parameters.

                // Save the file.
                doc.SaveAs(tempFileName, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsHTML, Microsoft.Office.Core.MsoTriState.msoFalse);

            }
            finally
            {
                // Make sure we close the application class.
                if (ac != null)
                    ac.Quit();
                System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
            }
        }
 private Document oDoc; // a reference to the document
 public ToWordDoc()
 {
     //
     // TODO: 在此处添加构造函数逻辑
     //
     // activate the interface with the COM object of Microsoft Word
     oWordApplic = new ApplicationClass();
 }
 public void MakeGraphs(string dir, bool includePearson, bool includeSpearman)
 {
     Application xlApp = new ApplicationClass();
     Workbook xlWorkBook = xlApp.Workbooks.Add(MisValue);
     List<Worksheet> workSheets = PopulateWorkSheets(xlWorkBook, includePearson, includeSpearman);
     dir = SaveFile(dir, xlWorkBook);
     ReleaseResources(xlApp, xlWorkBook, workSheets);
 }
Пример #19
0
        public Document openDocument(string filepath,ApplicationClass word)
        {
            Object filename = filepath;

            return word.Documents.Open(ref filename, ref unknow,
                        ref unknow, ref unknow, ref unknow, ref unknow,
                       ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                       ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
        }
Пример #20
0
        public int Convert(string sourcePath, string targetPath)
        {
            if (!File.Exists(sourcePath))
            {
                return ErrorMessages.FileNotExist;
            }
            XlFixedFormatType targetType = XlFixedFormatType.xlTypePDF;

            object missing = Type.Missing;
            ApplicationClass application = new ApplicationClass(); ;
            Workbook workBook = null;
            try
            {
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                                                      missing, missing, missing, missing, missing, missing, missing, missing, missing);
                //设置格式,导出成PDF
                Worksheet sheet = (Worksheet)workBook.Worksheets[1]; //下载从1开始
                //把sheet设置成横向
                sheet.PageSetup.Orientation = XlPageOrientation.xlLandscape;
                //可以设置sheet页的其他相关设置,不列举
                sheet.ExportAsFixedFormat(targetType,
                                            targetPath,
                                            XlFixedFormatQuality.xlQualityStandard,
                                            true,
                                            false,
                                            missing,
                                            missing,
                                            missing,
                                            missing);

                return ErrorMessages.ConvertSuccess;
            }
            catch (COMException ex)
            {
                _logger.Error(ex.StackTrace);
                _logger.Error(ex.Message);
                return ErrorMessages.OfficeToPdfUninstall;
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return ErrorMessages.ConvertFailed;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                }
                if (application != null)
                {
                    application.Quit();
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Пример #21
0
        public static void ExcelFromDataTable(System.Data.DataTable dt, string file)
        {
            // Create an Excel object and add workbook...
            ApplicationClass excel = new ApplicationClass();
            Workbook workbook = excel.Application.Workbooks.Add(Type.Missing);
            var worksheets = workbook.Sheets;
            var worksheet = (Worksheet)worksheets[1];

            // Add column headings...
            int iCol = 0;
            foreach (DataColumn c in dt.Columns)
            {
                iCol++;
                excel.Cells[1, iCol] = c.ColumnName.Trim();
            }

            WriteNumberFormatByColumn(dt.Rows.Count + 1, dt.Columns.Count + 1, worksheet);
            WriteArray(dt.Rows.Count, dt.Columns.Count, worksheet, dt.Rows);

            //// for each row of data...
            //int iRow = 0;
            //foreach (DataRow r in dt.Rows)
            //{
            //    iRow++;

            //    // add each row's cell data...
            //    iCol = 0;
            //    foreach (DataColumn c in dt.Columns)
            //    {
            //        iCol++;
            //        // data type format is Text
            //        ((Range)excel.Cells[iRow + 1, iCol]).NumberFormat = "@";
            //        excel.Cells[iRow + 1, iCol] = r[c.ColumnName].ToString().Trim();

            //    }
            //}

            // Global missing reference for objects we are not defining...
            object missing = System.Reflection.Missing.Value;

            //remove file
            //File.Delete(file);
            excel.DisplayAlerts = false;
            workbook.SaveAs(file,
                XlFileFormat.xlWorkbookNormal, missing, missing,
                false, false, XlSaveAsAccessMode.xlShared,
                false, false, missing, missing, missing);

            workbook.Close(false, missing, missing);

            excel.Quit();
            releaseObject(workbook);
            releaseObject(worksheets);
            releaseObject(excel);

        }
Пример #22
0
        public static RTDocument PPT2RTDwithSVG(string pptFilename)
        {
            //Pri2: Investigate where BasePath is and where we should be putting it in more depth.
            //      Concerned that we're creating directories there that never get cleaned up...
            if (!Directory.Exists(tfc.BasePath))
                Directory.CreateDirectory(tfc.BasePath);
            // Initialize PowerPoint app
            ApplicationClass ppt = new ApplicationClass();
            ppt.Visible = MsoTriState.msoTrue;

            // Open the PPT file
            Presentation presentation = ppt.Presentations.Open(pptFilename, MsoTriState.msoFalse, MsoTriState.msoTrue, MsoTriState.msoTrue);
            PrintOptions po = presentation.PrintOptions;
            po.ActivePrinter = @"SVGmaker";
            System.Threading.Thread.Sleep(6000);
            po.OutputType = PpPrintOutputType.ppPrintOutputSlides;
            po.PrintInBackground = MsoTriState.msoFalse;
            Slides slides = presentation.Slides;

            // Set up the document
            RTDocument rtDoc = new RTDocument();
            rtDoc.Identifier = Guid.NewGuid();
            rtDoc.Metadata.Title = GetPresentationProperty(ppt.ActivePresentation, "Title");
            rtDoc.Metadata.Creator = GetPresentationProperty(ppt.ActivePresentation, "Author");

            //Iterate through the pages
            foreach(Slide s in slides)
            {
                // Set the page properties
                Page p = new Page();
                p.Identifier = Guid.NewGuid();
                p.Extension = GetSlideSVG(presentation, s);
                p.MimeType = "image/svg";  // TODO: look up the real value for this
                rtDoc.Resources.Pages.Add(p.Identifier, p);

                // Set the TOCNode properties for the page
                TOCNode tn = new TOCNode();
                tn.Title = GetSlideTitle(s);
                tn.Resource = p;
                tn.ResourceIdentifier = p.Identifier;
                // TODO: Insert thumbnail? (tn.thumbnail)
                rtDoc.Organization.TableOfContents.Add(tn);
            }

            // Close PPT
            presentation.Close();
            if (ppt.Presentations.Count == 0)
            {
                ppt.Quit();
            }
            ppt = null;

            tfc.Delete();

            return rtDoc;
        }
Пример #23
0
        private void button2_Click(object sender, EventArgs e)
        {
            ApplicationClass XL = new ApplicationClass();
            XL.Visible = false;
            XL.Interactive = false;
            XL.ScreenUpdating = false;

            Workbook wb = XL.Workbooks.Add();
            Worksheet ws = (Worksheet)wb.Sheets[1];

            ((Range)ws.Cells[2, 1]).Value2 = "Permability, mD";
            ((Range)ws.Cells[2, 2]).Value2 = "Height, m";

            for (int iw = 0; iw < chart1.Series[0].Points.Count; ++iw )
            {
                ((Range)ws.Cells[iw + 4, 1]).Value2 = chart1.Series[0].Points[iw].XValue;
                ((Range)ws.Cells[iw + 4, 2]).Value2 = chart1.Series[0].Points[iw].YValues[0];
            }

            ((Range)ws.Cells[2, 4]).Value2 = "Position, m";
            ((Range)ws.Cells[2, 5]).Value2 = "Height, m";

            for (int iw = 1; iw < chart2.Series[0].Points.Count; ++iw)
            {
                ((Range)ws.Cells[iw + 3, 4]).Value2 = chart2.Series[0].Points[iw].XValue;
                ((Range)ws.Cells[iw + 3, 5]).Value2 = chart2.Series[0].Points[iw].YValues[0];
            }

            ((Range)ws.Cells[2, 7]).Value2 = "% OIP";
            ((Range)ws.Cells[2, 8]).Value2 = "Liquid rate, m3/day";
            ((Range)ws.Cells[2, 9]).Value2 = "Oil rate, m3/day";

            for (int iw = 0; iw < chart3.Series[0].Points.Count; ++iw)
            {
                ((Range)ws.Cells[iw + 4, 7]).Value2 = chart3.Series[0].Points[iw].XValue;
                ((Range)ws.Cells[iw + 4, 8]).Value2 = chart3.Series[0].Points[iw].YValues[0];
                ((Range)ws.Cells[iw + 4, 9]).Value2 = chart3.Series[1].Points[iw].YValues[0];
            }

            ((Range)ws.Cells[2, 11]).Value2 = "Sw";
            ((Range)ws.Cells[2, 12]).Value2 = "Krw";
            ((Range)ws.Cells[2, 13]).Value2 = "Kro";

            for (int iw = 0; iw < chart3.Series[0].Points.Count; ++iw)
            {
                ((Range)ws.Cells[iw + 4, 11]).Value2 = chart4.Series[0].Points[iw].XValue;
                ((Range)ws.Cells[iw + 4, 12]).Value2 = chart4.Series[0].Points[iw].YValues[0];
                ((Range)ws.Cells[iw + 4, 13]).Value2 = chart4.Series[1].Points[iw].YValues[0];
            }

            XL.Visible = true;
            XL.Interactive = true;
            XL.ScreenUpdating = true;
        }
Пример #24
0
        /// <summary>
        /// Create doc file with name pliking.doc into the application folder
        /// </summary>
        /// <param name="sStrSource">Text Language source</param>
        /// <param name="sStrDest">Text Language dest</param>
        /// <param name="sFileName">File name doc to create</param>
        /// <returns>true if the doc file is created</param>        
        public bool CreateDocFile(String sStrSource, String sStrDest, String sFileName)
        {
            object missing = System.Reflection.Missing.Value;
            object Visible=true;
            object start1 = 0;
            object end1 = 0;
            bool bRet = false;


            ApplicationClass WordApp = new ApplicationClass();
            Microsoft.Office.Interop.Word.Document adoc = WordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);
            Range rng = adoc.Range(ref start1, ref missing);
            String sFolder = sFileName.Substring(0, sFileName.LastIndexOf('\\'));
 
            try
            {              
                Object oSaveWithDocument = true;

                adoc.Tables.Add(rng, 3, 1, ref missing, ref missing);
                Range rngPic = adoc.Tables[1].Range;

                rngPic.InlineShapes.AddPicture(System.Windows.Forms.Application.StartupPath + "\\logo.jpg",
                    ref missing, ref oSaveWithDocument, ref missing);
                
                rng.Font.Name = "Verdana";
                rng.Font.Size = 12;
                rng.InsertAfter(sStrSource);
                rng.InsertAfter(sStrDest);

                foreach (Microsoft.Office.Interop.Word.Section section in adoc.Sections)
                {
                    object fieldEmpty = Microsoft.Office.Interop.Word.WdFieldType.wdFieldEmpty;
                    section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Name = "Verdana";
                    section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Size = 14;
                    section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Font.Bold = 1;
                    section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.InsertAfter("http://www.7touchgroup.com/");
                    section.Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary]
                    .Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
                }

                object filename = sFileName;
                adoc.SaveAs(ref filename, 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, ref missing, ref missing);
                //WordApp.Visible = true;
                bRet = true;
                adoc.Close(ref oSaveWithDocument, ref missing, ref missing);
            }
            catch (Exception ex)
            {
                Program.MainForm.AddLog("Exception:" + ex.Message, sFolder);
            }
            return bRet;
        }
Пример #25
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            /*
            Excel.Application app = new ApplicationClass();
            Workbooks workBooks = app.Workbooks;
            Workbook workBook = (Workbook )workBooks.GetType().InvokeMember("Open",BindingFlags.InvokeMethod,null,workBooks,new object[]{@"C:\Documents and Settings\raghunandanr\Desktop\Template Format for PDF Transcription1.xls"});
            workBook.PrintOut(Type.Missing,Type.Missing,1,false,Type.Missing,false,true,Type.Missing);
            workBook.Close(false,Type.Missing,Type.Missing);
            app.Quit();
            Marshal.ReleaseComObject(app);
            app = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            */
            Word.Application app=null;
            try
            {
                app = new ApplicationClass();
                //Document doc = new DocumentClass();
                Document doc  = (Document)typeof(Documents).InvokeMember("Open",BindingFlags.InvokeMethod,null,app.Documents,new object[]{@"C:\Documents and Settings\raghunandanr\Desktop\Word_template_prototype.doc"});
                object myTrue = true;
                object myFalse = false;
                object missingValue = Type.Missing;
                object range = WdPrintOutRange.wdPrintCurrentPage;
                object items = WdPrintOutItem.wdPrintDocumentContent;
                object copies = "1";
                object pages = "1";
                object pageType = WdPrintOutPages.wdPrintAllPages;

                doc.PrintOut(ref myTrue, ref myFalse, ref range,
                    ref missingValue, ref missingValue, ref missingValue,
                    ref items, ref copies, ref pages, ref pageType, ref myFalse,
                    ref myTrue, ref missingValue,  ref myFalse, ref missingValue,
                    ref missingValue, ref missingValue, ref missingValue);
               typeof(Document).InvokeMember("Close",BindingFlags.InvokeMethod,null,doc,new object[]{});
            }
            catch(Exception ex)
            {
                Response.Write(ex.Message);
                try
                {
                    if(app!=null)
                    {
                        typeof(Word.Application).InvokeMember("Quit",BindingFlags.InvokeMethod,null,app,new object[]{});
                        Marshal.ReleaseComObject(app);
                        app = null;
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }
                }
                catch{}
            }
        }
Пример #26
0
 static void Main(string[] args)
 {
     try
     {
         //if (args.Length < 2)
         //    args = new[] { @"C:\Users\Santhosh\Desktop\test1.docx", "999" };
         // return;
         string file = args[0].Replace("%20", " ");
         int id = Convert.ToInt32(args[1]);
         if (File.Exists(file) && !Utilities.IsFileUsedbyAnotherProcess(file))
         {
             switch (Path.GetExtension(file))
             {
                 case ".doc":
                 case ".docx":
                     {
                         var word = new ApplicationClass();
                         object miss = Missing.Value;
                         object path = file;
                         object readOnly = false;
                         var docs = word.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);
                         try
                         {
                             docs.ActiveWindow.Selection.WholeStory();
                             docs.ActiveWindow.Selection.Copy();
                             if (Clipboard.ContainsText())
                             {
                                 var data = Clipboard.GetText(TextDataFormat.Text);
                                 string url = Utilities.DevelopmentMode ? "http://localhost:3000" : "http://versavault.com";
                                 url += "/api/update_content?id=" + id + "&content=" + data;
                                 Utilities.GetResponse(url);
                             }
                         }
                         catch (Exception)
                         {
                             docs.Close(ref miss, ref miss, ref miss);
                         }
                         finally
                         {
                             if (docs != null)
                                 docs.Close(ref miss, ref miss, ref miss);
                         }
                         break;
                     }
             }
         }
     }
     catch (Exception)
     {
         return;
     }
 }
        public static void ExportToExcel(System.Data.DataTable data, string filename, Protocol.Structure.WaitObject wt)
        {
            if (data == null)
                return;
            var excel = new ApplicationClass();
            if (excel == null)
                throw new Exception("Excel无法启动");
            int rowNum = data.Rows.Count;
            var columns = data.Columns;
            int columnNum = columns.Count;
            wt.Flags = new int[1];
            wt.Max = rowNum * columnNum;
            int rowIndex = 1;
            int columnIndex = 0;
            var book = excel.Application.Workbooks.Add(true);
            try
            {
                foreach (DataColumn column in columns)
                {
                    columnIndex++;
                    excel.Cells[rowIndex, columnIndex] = column.ColumnName;
                    if (column.DataType == typeof(string))
                        excel.get_Range(excel.Cells[rowIndex + 1, columnIndex], excel.Cells[rowNum + 1, columnIndex]).NumberFormatLocal = "@";
                }
                for (int i = 0; i < rowNum; i++)
                {
                    rowIndex++;
                    columnIndex = 0;
                    for (int j = 0; j < columnNum; j++)
                    {
                        columnIndex++;
                        excel.Cells[rowIndex, columnIndex] = data.Rows[i][j];
                        wt.Flags[0]++;
                    }

                }
                excel.DisplayAlerts = false;
                excel.AlertBeforeOverwriting = false;
                book.SaveCopyAs(filename);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                book.Close(false);
                book = null;
                excel.Quit();
                excel = null;
            }
        }
Пример #28
0
        private void Create()
        {
            System.Globalization.CultureInfo Oldci = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            xlApp = new ApplicationClass();
            xlApp.Visible = true;

            xlWorkBook = xlApp.Workbooks.Add();
            xlWorkSheets = new List<Worksheet>();

            RemoveAllSheets(string.Empty);
        }
Пример #29
0
        /// <summary>
        /// Default Constructor of ExcelManager.
        /// </summary>
        /// <remarks>
        /// <example>Following example shows how to use this constructor:
        /// <code>
        /// using(ExcelManager em = new ExcelManager())
        /// {
        ///     // codes using excel file go here, for example:
        ///     em.Open(filename);
        /// }
        /// </code>
        /// </example>
        /// <b>Note:</b> This Constructor changes current thread's culture to "en-US" and returns it to 
        /// previous state after dispose.
        /// </remarks>
        public ExcelManager()
        {
            // During any access to the excel interop functions, current thread's culture must be "en-US".
            // We save current thread's culture, which will be restored in Dispose method
            OriginalCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            // Loads Excel
            App = new ApplicationClass();
            // Disables excel alerts (like save-as overwrite) which are meaningless during
            // programmatically access to excel
            App.DisplayAlerts = false;
        }
        public void exporta_a_excel()
        {
            ApplicationClass class2 = new ApplicationClass();
            class2.Application.Workbooks.Add(true);

            int num = 0;
            pBar1.Minimum = 1;
            pBar1.Maximum = dataGridView4.RowCount * dataGridView4.ColumnCount;
            pBar1.Value = 1;
            pBar1.Step = 1;

            foreach (DataGridViewColumn column in this.dataGridView4.Columns)
            {
               // class2.Cells[1, 1] = cmb_variedad.Text.Trim();

                if(column.Name.ToString() != "cod")
                {
                num++;
                class2.Cells[1, num] = column.Name;
                class2.get_Range("A1", "H1").Interior.ColorIndex = 9;
                class2.get_Range("A1", "H1").Font.ColorIndex = 2;
                class2.get_Range("A10", "H10").Interior.ColorIndex = 56;
                class2.get_Range("A10", "H10").Font.ColorIndex = 2;
                class2.get_Range("H1", "H10").Interior.ColorIndex = 56;
                class2.get_Range("H1", "H10").Font.ColorIndex = 2;
                class2.get_Range("A1", "H1").Borders.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);

                }
            }
            int num2 = 0;
            foreach (DataGridViewRow row in (IEnumerable)this.dataGridView4.Rows)
            {
                num2++;
                num = 0;
                foreach (DataGridViewColumn column2 in this.dataGridView4.Columns)
                {
                    if(column2.Name.ToString() != "cod")
                    {
                    num++;
                    class2.Cells[num2 + 1, num] = row.Cells[column2.Name].Value;

                    pBar1.PerformStep();
                    }

                }
            }
            class2.Visible = true;

            ((Worksheet)class2.ActiveSheet).Name = cmb_variedad.Text.Trim();
            ((Worksheet)class2.ActiveSheet).Activate();
        }
Пример #31
0
        public ErrorReporterForm(String message, int eaVersion)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            String s = "";

            s += "EA-Version: " + eaVersion + "\n";
            s += "Add-In-Version: " + typeof(VIENNAAddIn).Assembly.GetName().Name + " " +
                 typeof(VIENNAAddIn).Assembly.GetName().Version + "\n";
            s += ".NET version: " + Environment.Version + "\n";
            s += "OS version: " + Environment.OSVersion + "\n";

            String wordversion;

            try
            {
                var myWordApp = new ApplicationClass();
                wordversion = myWordApp.Version;
            }
            catch (Exception)
            {
                wordversion = "Not installed.";
            }

            s += "Word version: " + wordversion;

            message += "\n\n" + s;


            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            if (message != null)
            {
                this.message = message;
                errorMessageBox.AppendText(message);
            }

            Show();
        }
Пример #32
0
        private void InitializeWordApp()
        {
            if (_wordApp == null)
            {
                _wordApp = new ApplicationClass();
            }
            if (_hWnd == 0)
            {
                if (string.IsNullOrEmpty(_wordDocumentCaption))
                {
                    _hWnd = FindWindow("Opusapp", null);
                }
                else
                {
                    _hWnd = FindWindow("Opusapp", _wordDocumentCaption + " - Microsoft Word");
                }
            }

            if (_hWnd != 0)
            {
                SetParent(_hWnd, this.Handle.ToInt32());



                /// We want to remove the system menu also. The title bar is not visible, but we want to avoid accidental minimize, maximize, etc ..by disabling the system menu(Alt+Space)
                //try
                //{
                //    int hMenu = GetSystemMenu(_hWnd, false);
                //    if (hMenu > 0)
                //    {
                //        int menuItemCount = GetMenuItemCount(hMenu);
                //        DrawMenuBar(_hWnd);
                //    }
                //}
                //catch (Exception ex)
                //{
                //    MessageBox.Show(ex.Message);
                //}

                LoadBlankTemplate();
                //acitvateWordApp();
            }
        }
Пример #33
0
        public DataManager(IntPtr pParent)
        {
            oExcel               = null;
            oBook                = null;
            HistoricalData       = null;
            HistoricalDataSource = "";
            IsLiveSessionOpen    = false;

            //this.LiveSessionWorker.WorkerSupportsCancellation = true;
            //this.LiveSessionWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.LiveSessionWorker_DoWork);

            LiveSessionTimer.Elapsed += new System.Timers.ElapsedEventHandler(LiveSessionUpdate);
            ParentFormPtr             = pParent;

            UserProfile = new Profile();

            //Set the SSL/TLS security protocol to support TLS version 1.0, 1.1, and 1.2 (needed for HTTPS requests we use)
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        }
Пример #34
0
        internal bool BactchPrintCTByModel(string templateFileName, List <Dictionary <string, string> > ctCode, string printerName)
        {
            if (lbl == null)
            {
                lbl = new ApplicationClass();
            }
            //未加載模板文件或者模板發生變更時,重新加載新的模板
            if (lbl.Documents.Count == 0 || templateFileName.IndexOf(lbl.ActiveDocument.Name) == -1)
            {
                lbl.Documents.Open(templateFileName, false);// 调用设计好的label文件
            }
            Document doc = lbl.ActiveDocument;

            doc.Printer.SwitchTo(printerName);  //設置打印機
            try
            {
                foreach (Dictionary <string, string> ctDict in ctCode)
                {
                    for (int i = 1; i <= doc.Variables.FormVariables.Count; i++)
                    {
                        string variableName = doc.Variables.FormVariables.Item(i).Name.ToString();
                        doc.Variables.FormVariables.Item(i).Value = ctDict[variableName];
                    }
                    int Num = 1;
                    doc.PrintLabel(1, 1, 1, Num, 1, "");
                }
                doc.FormFeed();
            }
            catch (Exception ex)
            {
                return(false);                          //返回,後面代碼不執行
            }
            finally
            {
                //內存釋放和回收
                lbl.Documents.CloseAll();
                lbl.Quit();
                lbl = null;
                doc = null;
                GC.Collect(0);
            }
            return(true);
        }
Пример #35
0
        //word转换成HTML
        protected void btnChange_Click(object sender, EventArgs e)
        {
            string wordPath = Server.MapPath("/word/test.doc");
            string htmlPath = Server.MapPath("/html/test.html");

            //上传word文件, 由于只是做示例,在这里不多做文件类型、大小、格式以及是否存在的判断
            FileUpload1.SaveAs(wordPath);

            #region 文件格式转换
            //请引用Microsoft.Office.Interop.Word
            ApplicationClass word     = new ApplicationClass();
            Type             wordType = word.GetType();
            Documents        docs     = word.Documents;

            // 打开文件
            Type     docsType = docs.GetType();
            object   fileName = wordPath; //"f:\\cc.doc";
            Document doc      = (Document)docsType.InvokeMember("Open", BindingFlags.InvokeMethod, null, (object)docs, new Object[] { fileName, true, true });

            //判断与文件转换相关的文件是否存在,存在则删除。(这里,最好还判断一下存放文件的目录是否存在,不存在则创建)
            if (File.Exists(htmlPath))
            {
                File.Delete(htmlPath);
            }
            //每一个html文件,有一个对应的存放html相关元素的文件夹(html文件名.files)
            if (Directory.Exists(htmlPath.Replace(".html", ".files")))
            {
                Directory.Delete(htmlPath.Replace(".html", ".files"), true);
            }
            ;

            //转换格式,调用word的“另存为”方法
            Type   docType      = doc.GetType();
            object saveFileName = htmlPath; //"f:\\aaa.html";
            docType.InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML });

            // 退出 Word
            wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null);

            #endregion

            ifrm.Attributes.Add("src", "/html/test.html");
        }
        /// <summary>
        /// 在表格末端插入一行
        /// </summary>
        /// <param name="user">用户实例</param>
        public void InsertRow(User user)
        {
            ApplicationClass excelapp = new ApplicationClass();
            //excelapp.Visible = true;

            Workbook  workbook  = excelapp.Workbooks.Open(FilePath, Type.Missing, false, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets.get_Item(1);
            int       iRowCount = worksheet.UsedRange.Rows.Count;

            worksheet.Cells[iRowCount + 1, 1] = user.UserId;
            worksheet.Cells[iRowCount + 1, 2] = user.UserName;
            worksheet.Cells[iRowCount + 1, 3] = user.UserAge;

            //workbook.SaveAs(FilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            workbook.Close(true, Missing.Value, Missing.Value);
            excelapp.Workbooks.Close();
            excelapp.Quit();
            KillThread(excelapp);
        }
Пример #37
0
        /// <summary>
        /// 打开一个Excel
        /// </summary>
        /// <param name="xlsFilePath"></param>
        public V_Excel_Helper(string xlsFilePath)
        {
            App         = new ApplicationClass();
            App.Visible = false;
            WB          = App.Workbooks.Open(xlsFilePath, 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);
            int count = WB.Worksheets.Count;

            for (int i = 1; i <= count; i++)
            {
                WS_List = new List <Worksheet>();
                Worksheet wS = (Worksheet)WB.Worksheets.Item[i];
                if (wS.Visible == XlSheetVisibility.xlSheetVisible)
                {
                    WS_List.Add(wS);
                }
            }
            HwndOfApp         = App.Hwnd;
            this._xlsFilePath = XlsFilePath;
        }
Пример #38
0
        /// <summary>生成PDF文件</summary>
        public override bool Execute(string sourceFile, string pdfFile, string destFile)
        {
            ApplicationClass application  = null;
            Presentation     presentation = null;

            try
            {
                application  = new ApplicationClass();
                presentation = application.Presentations.Open(sourceFile, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
                var sBuilder = new StringBuilder();
                foreach (Slide slide in presentation.Slides)
                {
                    foreach (Microsoft.Office.Interop.PowerPoint.Shape shape in slide.Shapes)
                    {
                        if (shape.HasTextFrame != MsoTriState.msoTrue)
                        {
                            continue;
                        }
                        var textFrame = shape.TextFrame;
                        if (textFrame.HasText != MsoTriState.msoTrue)
                        {
                            continue;
                        }
                        sBuilder.AppendLine(textFrame.TextRange.Text);
                    }
                }
                return(WriteFile(destFile, sBuilder.ToString()));
            }
            finally
            {
                if (presentation != null)
                {
                    presentation.Close();
                    Marshal.ReleaseComObject(presentation);
                }
                if (application != null)
                {
                    application.Quit();
                    Marshal.ReleaseComObject(application);
                }
            }
        }
Пример #39
0
        static void Main(string[] args)
        {
            var applicationClass = new ApplicationClass();
            //applicationClass.Visible = false; 默认值就是 false 值
            var    folder   = Environment.CurrentDirectory;
            string fileName = "1.docx";

            fileName = Path.Combine(folder, fileName);
            fileName = Path.GetFullPath(fileName);

            // 截图使用只读方式打开,这里传入的要求是绝对路径
            Document document = applicationClass.Documents.Open(fileName, ReadOnly: true);

            var count = 0;

            foreach (Window documentWindow in document.Windows)
            {
                var documentWindowPanes = documentWindow.Panes;
                for (var index = 0; index < documentWindowPanes.Count; index++)
                {
                    Pane documentWindowPane = documentWindowPanes[index + 1];
                    var  pagesCount         = documentWindowPane.Pages.Count;
                    for (int i = 0; i < pagesCount; i++)
                    {
                        Page page = documentWindowPane.Pages[i + 1];
                        Console.WriteLine($"{page.Width};{page.Height}");
                        count++;
                        var file = Path.Combine(folder, $"{count}.png");

                        var bits = page.EnhMetaFileBits;
                        using (var ms = new MemoryStream((byte[])(bits)))
                        {
                            var image = System.Drawing.Image.FromStream(ms);
                            image.Save(file);
                        }
                        //page.SaveAsPNG(file); // System.Runtime.InteropServices.COMException: '该方法无法用于对那个对象。'
                    }
                }
            }

            document.Close();
        }
Пример #40
0
        private void DataToExcel(string title, string sheetName, string filename, System.Data.DataTable dt)
        {
            saveFileDialog1.Filter   = "EXCEL文件(*.xls)|*.xls";
            saveFileDialog1.Title    = title;
            saveFileDialog1.FileName = filename;
            saveFileDialog1.ShowDialog();
            MessageBox.Show("亲~转换要一些时间哦", "温馨提示");
            ApplicationClass ExcelApp = new ApplicationClass();
            Workbook         wb       = ExcelApp.Workbooks.Add();
            Worksheet        st       = ((Worksheet)wb.ActiveSheet);

            st.Name = sheetName;
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                st.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++)
                {
                    st.Cells[i + 2, j + 1] = dt.Rows[i][j].ToString();
                }
                if (dt.Columns.Contains("EnNo"))
                {
                    GatherDuty.GetDutyInfo(dt.Rows[i]);
                    st.Cells[i + 2, dt.Columns.Count + 1] = GatherDuty.GetRemark(dt.Rows[i]);
                }
            }
            Microsoft.Office.Interop.Excel.Range oRange = st.get_Range(st.Cells[1, 1],
                                                                       st.Cells[dt.Rows.Count + 1, dt.Columns.Count]);
            oRange.EntireColumn.AutoFit();
            wb.SaveAs(saveFileDialog1.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                      Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value);
            wb.Close(Missing.Value);
            wb = null;
            ExcelApp.Quit();
            ExcelApp = null;
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }
Пример #41
0
        /// <summary>
        /// 执行转换
        /// </summary>
        public void Convert()
        {
            ApplicationClass word     = new ApplicationClass();
            Type             wordType = word.GetType();
            Documents        docs     = word.Documents;

            Type     docsType = docs.GetType();
            Document document = (Document)docsType.InvokeMember("Open", BindingFlags.InvokeMethod, null, docs, new Object[] { InputFile, true, true });
            Type     doctype  = document.GetType();

            TempFile = new FileInfo(Server.MapPath("/UpFiles/Temp/temp") + Path.GetExtension(SaveFile));
            FileHelper.CreatePath(TempFile.FullName);

            #region

            /*
             * 下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成:
             * docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
             * null, doc, new Object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML});
             * 其它格式:
             * wdFormatHTML
             * wdFormatDocument
             * wdFormatDOSText
             * wdFormatDOSTextLineBreaks
             * wdFormatEncodedText
             * wdFormatRTF
             * wdFormatTemplate
             * wdFormatText
             * wdFormatTextLineBreaks
             * wdFormatUnicodeText
             */
            #endregion

            doctype.InvokeMember("SaveAs", BindingFlags.InvokeMethod, null, document, new Object[] { TempFile.FullName, SaveFormat });
            wordType.InvokeMember("Quit", BindingFlags.InvokeMethod, null, word, null);

            if (SaveFormat != WdSaveFormat.wdFormatFilteredHTML)
            {
                File.Copy(TempFile.FullName, SaveFile);
                ClearTemp();
            }
        }
Пример #42
0
        static void Main(string[] args)
        {
            string Path = System.Windows.Forms.Application.StartupPath + "\\sample.xlsx";

            // initialize the Excel Application class
            ApplicationClass app = new ApplicationClass();

            // create the workbook object by opening the excel file.
            Workbook workBook = app.Workbooks.Open(Path, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

            // get the active worksheet using sheet name or active sheet
            Worksheet workSheet = (Worksheet)workBook.ActiveSheet;

            // This row,column index should be changed as per your need, i.e. which cell in the excel you are interesting to read.

            int row_index = 2;
            int first_name_column_index = 1;
            int last_name_column_index  = 2;

            try
            {
                while (((Range)workSheet.Cells[row_index, first_name_column_index]).Value2 != null)
                {
                    string firstName =
                        ((Range)workSheet.Cells[row_index, first_name_column_index]).Value2.ToString();
                    string lastName =
                        ((Range)workSheet.Cells[row_index, last_name_column_index]).Value2.ToString();
                    Console.WriteLine("Name : {0} {1} ", firstName, lastName);
                    row_index++;
                }
                workBook.Close();
                app.Quit();
            }
            catch (Exception ex)
            {
                workBook.Close();
                app.Quit();
                Console.WriteLine(ex.Message);
            }

            Console.ReadKey();
        }
Пример #43
0
        /// <summary>
        /// 通過codesoft打印lab格式模板,外部傳入已經實例化的codesoft的application class,並且打印完畢后不釋放,以提高速度,需要在打印完畢后調用ReleaseCodeSoftObj來釋放
        /// </summary>
        /// <param name="ac">LabelManager2.ApplicationClass</param>
        /// <param name="doc">LabelManager2.Document</param>
        /// <param name="dt">文件名使用變量名FILENAME(例如123.lab),不含路徑,文件需放在程序目錄下,其它列的變量就是要替換的變量名稱,DataTable列頭以&lt;變量名&gt;為格式,替換lab文檔中相同的變量</param>
        public static void PrintByLabFile(ApplicationClass ac, Document doc, DataTable dt)
        {
            string strFilePath = System.Windows.Forms.Application.StartupPath + "\\" + dt.Rows[0]["FILENAME"].ToString();

            if (!File.Exists(strFilePath))
            {
                throw new Exception("Can not find the templet:" + @strFilePath);
            }

            try
            {
                Strings vars    = ac.PrinterSystem().Printers(enumKindOfPrinters.lppxAllPrinters);
                string  printer = GetDefaultPrinterName();
                #region 檢查打印機(暫時無用)
                //for (int i = 0; i < vars.Count; i++)
                //{
                //    string csPrinter = vars.Item(i);
                //    if (csPrinter.IndexOf(lblPrinter.Text) >= 0)
                //    {
                //        printer = csPrinter;
                //        break;
                //    }
                //}
                #endregion

                List <string> varList = GetVarList(ac, doc);
                if (varList == null)
                {
                    throw new Exception("獲取LAB變量失敗");
                }

                PrintLab(printer, ac, doc, dt, strFilePath, varList);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                //不釋放文檔對象,避免重建浪費時間,但是在主程序裡面一定要有釋放代碼,以免文件被佔用
            }
        }
Пример #44
0
        public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
        {
            if (tmpDataTable == null)
            {
                return;
            }

            int rowNum      = tmpDataTable.Rows.Count;
            int columnNum   = tmpDataTable.Columns.Count;
            int rowIndex    = 1;
            int columnIndex = 0;

            Application xlApp = new ApplicationClass();

            xlApp.DefaultFilePath     = "";
            xlApp.DisplayAlerts       = true;
            xlApp.SheetsInNewWorkbook = 1;
            Workbook xlBook = xlApp.Workbooks.Add(true);

            //将DataTable的列名导入Excel表第一行
            foreach (DataColumn dc in tmpDataTable.Columns)
            {
                columnIndex++;
                xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
            }

            //将DataTable中的数据导入Excel中

            for (int i = 0; i < rowNum; i++)
            {
                rowIndex++;
                columnIndex = 0;
                for (int j = 0; j < columnNum; j++)
                {
                    columnIndex++;
                    xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();
                }
            }
            //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));
            xlBook.SaveCopyAs(strFileName);
            xlBook.Close(false);
        }
Пример #45
0
        public void PublicPrintLabel(Dictionary <string, string> dic)
        {
            if (!File.Exists(LabelFlePatch.Text))  //判断条码文件是否存在
            {
                mFrm.ShowMsg(Frm_MaterialManage.mLogMsgType.Error, "条码档没有找到,路径:" + LabelFlePatch.Text);
                return;
            }
            ApplicationClass lbl = new ApplicationClass();

            try
            {
                lbl.Documents.Open(LabelFlePatch.Text, false);// 调用设计好的label文件
                Document doc = lbl.ActiveDocument;
                for (int i = 0; i < doc.Variables.FormVariables.Count; i++)
                {
                    doc.Variables.FormVariables.Item(doc.Variables.FormVariables.Item(i + 1).Name).Value = "";
                }
                mFrm.ShowMsg(Frm_MaterialManage.mLogMsgType.Incoming, string.Format("模板变量清空完成,共计{0}个...", doc.Variables.FormVariables.Count));
                foreach (KeyValuePair <string, string> _DicKeyValues in dic)
                {
                    try
                    {
                        doc.Variables.FormVariables.Item(_DicKeyValues.Key).Value = _DicKeyValues.Value; //给参数传值
                        mFrm.ShowMsg(Frm_MaterialManage.mLogMsgType.Outgoing, string.Format("填充打印变量完成:{0}->{1}", _DicKeyValues.Key, _DicKeyValues.Value));
                    }
                    catch
                    {
                    }
                }
                int Num = Convert.ToInt32(numPrintQty.Value); //打印数量
                doc.PrintDocument(Num);                       //打印
                mFrm.ShowMsg(Frm_MaterialManage.mLogMsgType.Normal, "打印完成");
            }
            catch (Exception ex)
            {
                mFrm.ShowMsg(Frm_MaterialManage.mLogMsgType.Error, "发生异常" + ex.Message);
            }
            finally
            {
                lbl.Quit(); //退出
            }
        }
Пример #46
0
        protected virtual void Dispose(bool isDisposing)
        {
            if (myExcel != null)
            {
                myWriter.Dispose();
                myWriter = null;

                EnableAutoFilter();
                Save();
                myWorkbook = null;

                // Close excel when nothing has been written.
                if (mybCloseOnDispose || myTotalLinesWritten == 0)
                {
                    myExcel.Quit();
                }

                myExcel = null;
            }
        }
Пример #47
0
        internal static IAcqMethod GetAcqMethod(string methodFilePath, out MassSpecMethod templateMsMethod)
        {
            ApplicationClass analyst = new ApplicationClass();

            // Make sure that Analyst is fully started
            IAcqMethodDirConfig acqMethodDir = (IAcqMethodDirConfig)analyst.Acquire();

            if (acqMethodDir == null)
            {
                throw new IOException("Failed to initialize.  Analyst may need to be started.");
            }

            object acqMethodObj;

            acqMethodDir.LoadNonUIMethod(methodFilePath, out acqMethodObj);
            IAcqMethod templateAcqMethod = (IAcqMethod)acqMethodObj;

            templateMsMethod = ExtractMsMethod(templateAcqMethod);
            return(templateAcqMethod);
        }
Пример #48
0
 public void multiHightLigthKeyWord(string preMultiTestFilePath, string preMultiRegFilePath, string preMultiSpecFilePath, string multiTestFilePath, string multiRegFilePath, string multiSpecFilePath,
                                    string keyWord, ApplicationClass testWord, RichTextBox rtbTest, RichTextBox rtbReg, RichTextBox rtbSpecification, Label test, Label reg,
                                    Label spec, RichTextBox testStatisticsInfor, RichTextBox regStatisticsInfor, RichTextBox specStatisticsInfor, HandleDocument handleDocument, Boolean isKeyChanged)
 {
     if (checkFilePathInput(multiTestFilePath, multiRegFilePath, multiSpecFilePath) == true)
     {
         if (multiTestFilePath != "" && (!multiTestFilePath.Equals(preMultiTestFilePath) || isKeyChanged))
         {
             anyOneDocHighLigth(multiTestFilePath, testWord, keyWord, rtbTest, test, testStatisticsInfor, handleDocument);
         }
         if (multiRegFilePath != "" && (!multiRegFilePath.Equals(preMultiRegFilePath) || isKeyChanged))
         {
             anyOneDocHighLigth(multiRegFilePath, testWord, keyWord, rtbReg, reg, regStatisticsInfor, handleDocument);
         }
         if (multiSpecFilePath != "" && (!multiSpecFilePath.Equals(preMultiSpecFilePath) || isKeyChanged))
         {
             anyOneDocHighLigth(multiSpecFilePath, testWord, keyWord, rtbSpecification, spec, specStatisticsInfor, handleDocument);
         }
     }
 }
Пример #49
0
        public ActionResult SetSort(string entityId, string sortValue)
        {
            AjaxResult    result = new AjaxResult(AjaxResultStatus.Success, string.Empty);
            StringBuilder sbMsg  = new StringBuilder();

            try
            {
                ApplicationClass entity = m_FTISService.GetApplicationClassById(Convert.ToInt32(entityId));
                entity.SortId = int.Parse(sortValue);
                m_FTISService.UpdateApplicationClass(entity);
            }
            catch (Exception ex)
            {
                result.ErrorCode = AjaxResultStatus.Fail;
                sbMsg.AppendFormat(ex.Message + "<br/>");
            }

            result.Message = sbMsg.ToString();
            return(this.Json(result));
        }
Пример #50
0
        private void StartExcel(int index)
        {
            if (index < 0 || index > this._templates.Length)
            {
                return;
            }
            lock (this._working)
            {
                if (this._excelInWork)
                {
                    return;
                }
                this._excelInWork = true;
                this._exApp       = (ApplicationClass) new Microsoft.Office.Interop.Excel.Application();

                this._exWbk = _exApp.Workbooks.Open(this._templates[index], Type.Missing, true);

                this._exSht = (Worksheet)this._exWbk.Sheets[_sheets[index]];
            }
        }
Пример #51
0
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 private Excel.ApplicationClass OpenExcel()
 {
     try
     {
         string xlsFileName = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) +
                              "\\report\\rptWcMonth.xls";
         Excel.ApplicationClass excelCls = new ApplicationClass();
         Excel.Workbook         excelWb  = excelCls.Workbooks.Add(xlsFileName);
         return(excelCls);
     }
     catch (Exception ex)
     {
         MsgBox.Show(
             ex.ToString(),
             "错误",
             MessageBoxIcon.Error
             );
         return(null);
     }
 }
Пример #52
0
 public LicenseModel GetById(int id)
 {
     return(_context.Licenses.Where(x => x.Id == id).Select(x => new LicenseModel
     {
         Id = x.Id,
         IdClient = x.IdClients,
         ClientName = ClientClass.GetClientName(x.IdClients),
         IsActive = x.IsActive,
         Creation = x.Creation,
         IdApplication = x.IdApplication,
         PermissionsModel = PermissionClass.ConvertPermission(x.Permissions),
         Number = x.Number,
         AssignedVersion = x.AssignedVersion,
         Inclusion = x.Inclusion,
         IsActivated = x.IsActivated,
         IdentityNumber = x.IdentityNumber,
         Expiration = x.Expiration,
         ApplicationModel = ApplicationClass.ConvertPermission(x.Application)
     }).FirstOrDefault());
 }
Пример #53
0
 /// <remarks>
 /// As a part of Disposable pattern, releases resources and return thread's CurrentCulture to its original state.
 /// </remarks>
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposedValue)
     {
         if (disposing)
         {
             if (App != null)
             {
                 // Disables excel alerts (like save-as overwrite) which are meaningless during
                 // programmatically access to excel
                 App.DisplayAlerts = true;
                 Close();
                 App.Quit();
                 App = null;
                 Thread.CurrentThread.CurrentCulture = OriginalCulture;
             }
         }
     }
     _disposedValue = true;
 }
Пример #54
0
        public ObservableCollection <string> ExportSlide(string path)
        {
            ObservableCollection <string> paths = new ObservableCollection <string>();

            ApplicationClass pptApplication  = new ApplicationClass();
            Presentation     pptPresentation = pptApplication.Presentations.Open(path, MsoTriState.msoFalse,
                                                                                 MsoTriState.msoFalse, MsoTriState.msoFalse);

            int counter = 0;

            foreach (Slide slide in pptPresentation.Slides)
            {
                string destpath = Environment.CurrentDirectory + "\\slide" + counter + ".png";
                slide.Export(destpath, "png");
                paths.Add(destpath);
                counter++;
            }

            return(paths);
        }
Пример #55
0
        private void eventopenlablefile(string filename)
        {
            if (!Directory.Exists(System.IO.Directory.GetCurrentDirectory() + @"\Print"))
            {
                Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + @"\Print");
            }
            if (!File.Exists(filename))  //判断条码文件是否存在
            {
                this.isprinter = false;
                ShowMP.ShowPrgMsg("条码档没有找找到,正在从Ftp下载..", MainParent.MsgType.Warning);
                FrmBLL.Ftp_MyFtp ftp = new FrmBLL.Ftp_MyFtp();
                ftp.DownloadFile("FEIXUN_LOT.Lab", System.AppDomain.CurrentDomain.BaseDirectory + "Print", "FEIXUN_LOT.Lab");
                ShowMP.ShowPrgMsg("下载完成", MainParent.MsgType.Outgoing);
                // ShowMP.ShowPrgMsg("条码档没有找找到,请确认当前目录是否存在 FEIXUN_LOT.lab", MainParent.MsgType.Error);
            }

            this.isprinter = true;
            lbl            = new ApplicationClass();
            lbl.Documents.Open(labelfilepatch.Text.Trim(), false);// 调用设计好的label文件
        }
Пример #56
0
        public void generateTOC(Document doc, ApplicationClass app)
        {
            Object oMissing           = System.Reflection.Missing.Value;
            Object oTrue              = true;
            Object oFalse             = false;
            Object oUpperHeadingLevel = "1";
            Object oLowerHeadingLevel = "3";
            Object oTOCTableID        = "TableOfContents";

            app.Selection.Start = 0;
            app.Selection.End   = 0;            //将光标移动到文档开始位置
            object beginLevel = 2;              //目录开始深度
            object endLevel   = 2;              //目录结束深度

            object rightAlignPageNumber = true; // 指定页码右对其

            doc.TablesOfContents.Add(app.Selection.Range, ref oTrue, ref oUpperHeadingLevel,
                                     ref oLowerHeadingLevel, ref oMissing, ref oTOCTableID, ref oTrue,
                                     ref oTrue, ref oMissing, ref oTrue, ref oTrue, ref oTrue);
        }
Пример #57
0
        static void Main(string[] args)
        {
            //WordFileToRead.SaveAs(Server.MapPath(WordFileToRead.FileName));
            object           filename = @"F:\Users\Arche\Desktop\Project.docx";//Server.MapPath(WordFileToRead.FileName);
            ApplicationClass AC       = new ApplicationClass();

            Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
            object readOnly  = false;
            object isVisible = true;
            object missing   = System.Reflection.Missing.Value;

            try
            {
                doc = AC.Documents.Open(ref filename, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref isVisible, ref missing, ref missing, ref missing);
                WordFileText.Text = doc.Content.Text;
            }
            catch (Exception ex)
            {
            }
        }
Пример #58
0
 public IEnumerable <LicenseModel> GetLicensesModelByApplication(int idApp)
 {
     return(_context.Licenses.Where(x => x.IdApplication == idApp).Select(x => new LicenseModel()
     {
         Id = x.Id,
         IdClient = x.IdClients,
         ClientName = ClientClass.GetClientName(x.IdClients),
         IsActive = x.IsActive,
         Creation = x.Creation,
         IdApplication = x.IdApplication,
         PermissionsModel = PermissionClass.ConvertPermission(x.Permissions),
         Number = x.Number,
         AssignedVersion = x.AssignedVersion,
         Inclusion = x.Inclusion,
         IsActivated = x.IsActivated,
         IdentityNumber = x.IdentityNumber,
         Expiration = x.Expiration,
         ApplicationModel = ApplicationClass.ConvertPermission(x.Application)
     }));
 }
Пример #59
0
        public static void SaveAsExcel(DataSet ds, string saveType, string outputFile)
        {
            ApplicationClass excelApp = new ApplicationClass();

            excelApp.Visible = false;

            //设置禁止弹出保存和覆盖的询问提示框
            excelApp.DisplayAlerts          = false;
            excelApp.AlertBeforeOverwriting = false;
            object missing = System.Reflection.Missing.Value;

            if (saveType == "sheet")
            {
                //新建一个WorkBook
                Workbook workBook = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    ArrayToExcel((Worksheet)workBook.Sheets.Add(), TableToArray(ds.Tables[i]), 1, 0);
                }
                try
                {
                    workBook.SaveAs(outputFile, missing, missing, missing, missing, missing, XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
                }
                catch (Exception e)
                {
                    System.Windows.Forms.MessageBox.Show(e.Message);
                }
                finally
                {
                    if (workBook != null)
                    {
                        workBook.Close(null, null, null);
                    }
                    if (excelApp != null)
                    {
                        excelApp.Workbooks.Close();
                        excelApp.Quit();
                    }
                }
            }
        }
Пример #60
0
        void ConvertDocument(string fileName)
        {
            object           m           = System.Reflection.Missing.Value;
            object           oldFileName = (object)fileName;
            object           readOnly    = (object)false;
            ApplicationClass ac          = null;

            try
            {
                // First, create a new Microsoft.Office.Interop.Word.ApplicationClass.
                ac = new ApplicationClass();

                // Now we open the document.
                Document doc = ac.Documents.Open(ref oldFileName, 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);

                // Create a temp file to save the HTML file to.
                tempFileName = GetTempFile("html");

                // Cast these items to object.  The methods we're calling
                // only take object types in their method parameters.
                object newFileName = (object)tempFileName;

                // We will be saving this file as HTML format.
                object fileType = (object)WdSaveFormat.wdFormatHTML;

                // Save the file.
                doc.SaveAs(ref newFileName, ref fileType,
                           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);
            }
            finally
            {
                // Make sure we close the application class.
                if (ac != null)
                {
                    ac.Quit(ref readOnly, ref m, ref m);
                }
            }
        }