Example #1
0
        private void copySheetToClipboard()
        {
            //create cashflow worksheet
            string    name   = "Cash Flow";
            bool      exists = false;
            Worksheet ws     = Globals.ThisAddIn.GetWorksheet();
            Workbook  wb     = Globals.ThisAddIn.Application.ActiveWorkbook;

            foreach (Worksheet sheets in wb.Worksheets)
            {
                if (sheets.Name.Equals(name))
                {
                    ws = sheets;
                    sheets.Activate();
                    sheets.Visible = XlSheetVisibility.xlSheetVisible;
                }
            }

            Range rnge = ws.Range["A1", form7.cellrg];

            rnge.Interior.Color = Microsoft.Office.Interop.Excel.XlRgbColor.rgbWhite;
            rnge.CopyPicture(Microsoft.Office.Interop.Excel.XlPictureAppearance.xlScreen, Microsoft.Office.Interop.Excel.XlCopyPictureFormat.xlBitmap);


            Clipboard.GetImage().Save("C:\\Users\\admin\\Source\\Repos\\BusinessPlanWriter\\BPWChartImages\\CashFlow.bmp", ImageFormat.Bmp);
        }
Example #2
0
        public static void ExportNamedRanges()
        {
            OfceExcel.Workbook WB = MyApp.ExcelApp.ActiveWorkbook;

            foreach (OfceExcel.Name NamedRange in WB.Names)
            {
                try
                {
                    OfceExcel.Range CurRange = NamedRange.RefersToRange;
                    CurRange.CopyPicture(OfceExcel.XlPictureAppearance.xlScreen, OfceExcel.XlCopyPictureFormat.xlBitmap);
                    MyApp.Fullpathname = MyApp.ExcelApp.ActiveWorkbook.Path + "\\" + WB.Name + "_" + NamedRange.Name + ".png";
                    sysImg.Imaging.ImageFormat PngFormat = sysImg.Imaging.ImageFormat.Png;
                    bool result = MyApp.SaveImage(MyApp.Fullpathname, PngFormat);
                }
                catch { }
                finally { }
            }



            foreach (OfceExcel.Worksheet WS in WB.Worksheets)
            {
                foreach (OfceExcel.Name NamedRange in WS.Names)
                {
                }
            }
        }
Example #3
0
        private void button16_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application eApp = new Microsoft.Office.Interop.Excel.Application();
            eApp.Visible = true;
            Microsoft.Office.Interop.Excel.Workbook workBook = eApp.Workbooks.Open(@"e:/2.xlsx");
            Worksheet  sheet = workBook.ActiveSheet;
            PivotTable pt    = sheet.PivotTables()[1];

            Microsoft.Office.Interop.Excel.Range range = pt.TableRange2;
            range.CopyPicture(XlPictureAppearance.xlScreen, XlCopyPictureFormat.xlPicture);
            Worksheet newSheet = workBook.Sheets.Add();
            //newSheet.Paste();
            //Microsoft.Office.Interop.Excel.Shape s = newSheet.Shapes.Item(1);
            //s.Chart.Export(@"e:\2.png", "PNG");

            ChartObjects objs     = newSheet.ChartObjects();
            ChartObject  chartobj = objs.Add(0, 0, range.Width, range.Height);

            //if (chartobj.Chart != null)
            chartobj.ProtectChartObject = false;
            chartobj.Chart.Paste();
            chartobj.Chart.Export(@"e:\1.png", "PNG");
            chartobj.Delete();
            eApp.Quit();
        }
Example #4
0
    /// <summary>
    /// 將Excel的Sheet轉成Image
    /// </summary>
    /// <param name="sheet">工作表</param>
    /// <param name="inFrom">起始位子</param>
    /// <param name="inTo">結束位子</param>
    /// <returns></returns>
    private System.Drawing.Image SheetToImage(Excel1.Worksheet sheet, string inFrom, string inTo)
    {
        Excel1.Range         range   = null;
        System.Drawing.Image ToImage = null;

        try
        {
            range = sheet.get_Range(inFrom, inTo);

            range.CopyPicture(Excel1.XlPictureAppearance.xlScreen, Excel1.XlCopyPictureFormat.xlBitmap);

            ToImage = System.Windows.Forms.Clipboard.GetImage();


            _Excel = null;
        }
        catch (Exception ex)
        {
            //throw new System.Exception(ex.Message.ToString());
        }
        finally
        {
            System.Windows.Forms.Clipboard.Clear();
        }

        return(ToImage);
    }
Example #5
0
        private void CopyPictureExcelPage(Excel.Worksheet xlsSheet, int sl, int sc, int el, int ec)
        {
            Excel.Range xlsAreaRng = null;
            Excel.Range xlsRngS    = null;
            Excel.Range xlsRngE    = null;

            xlsRngS    = xlsSheet.Cells[sl, sc];
            xlsRngE    = xlsSheet.Cells[el, ec];
            xlsAreaRng = xlsSheet.get_Range(xlsRngS, xlsRngE);
            xlsAreaRng.CopyPicture();
        }
Example #6
0
        public static int readone(int i)
        {
            Excel.Range ran       = null;
            string      url       = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Picture";
            int         rowscount = exws.UsedRange.Rows.Count;
            int         colscount = exws.UsedRange.Columns.Count;
            string      id        = String.Empty;
            string      name      = String.Empty;
            string      imagepath = String.Empty;
            string      attr      = String.Empty;
            int         phattack;
            int         phdefense;
            int         spattack;
            int         spdefense;
            int         hp;
            int         speed;
            int         sum;

            id        = ((Excel.Range)exws.Cells[i, 1]).Text.ToString();
            name      = ((Excel.Range)exws.Cells[i, 2]).Text.ToString();
            imagepath = url + "\\" + name + ".png";
            if (!File.Exists(imagepath))
            {
                ran = exws.Cells[i, 3];
                ran.Select();
                ran.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);
                ParameterizedThreadStart tstart = new ParameterizedThreadStart(Saveimg);
                Thread thread = new Thread(tstart);
                thread.SetApartmentState(ApartmentState.STA);
                thread.Start(imagepath);
            }
            attr      = ((Excel.Range)exws.Cells[i, 4]).Text.ToString();
            hp        = Convert.ToInt32(((Excel.Range)exws.Cells[i, 5]).Text.ToString());
            phattack  = Convert.ToInt32(((Excel.Range)exws.Cells[i, 6]).Text.ToString());
            phdefense = Convert.ToInt32(((Excel.Range)exws.Cells[i, 7]).Text.ToString());
            spattack  = Convert.ToInt32(((Excel.Range)exws.Cells[i, 8]).Text.ToString());
            spdefense = Convert.ToInt32(((Excel.Range)exws.Cells[i, 9]).Text.ToString());
            speed     = Convert.ToInt32(((Excel.Range)exws.Cells[i, 10]).Text.ToString());
            sum       = Convert.ToInt32(((Excel.Range)exws.Cells[i, 11]).Text.ToString());
            PokemonList.Add(new Pokemon(id, name, imagepath,
                                        attr, phattack, phdefense, spattack,
                                        spdefense, hp, sum, speed));
            finishcount++;
            if (finishcount % 100 == 0 && finishcount / 100 != 0)
            {
                ExcelApi.Dispose();
                ExcelApi.Init(filename);
            }
            return(finishcount);
        }
Example #7
0
        public Image GetImage()
        {
            AssertNotDisposed();
            Excel.Range _range = _GetRange();
            Image       image  = null;

            lock (Synchronization.ClipboardSyncRoot)
            {
                _range.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);
                if (Clipboard.ContainsImage())
                {
                    image = Clipboard.GetImage();
                }
            }

            Marshal.ReleaseComObject(_range);
            return(image);
        }
    static void Main(string[] args)
    {
        Excel.Application excel = new Excel.Application();
        Excel.Workbook    wkb   = excel.Workbooks.Add(Type.Missing);
        Excel.Worksheet   sheet = wkb.Worksheets[1] as Excel.Worksheet;
        Excel.Range       range = sheet.Cells[1, 1] as Excel.Range;
        range.Formula = "Hello World";

        // copy as seen when printed
        range.CopyPicture(Excel.XlPictureAppearance.xlPrinter, Excel.XlCopyPictureFormat.xlPicture);

        // uncomment to copy as seen on screen
        //range.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlBitmap);

        Console.WriteLine("Please enter a full file name to save the image from the Clipboard:");
        string fileName = Console.ReadLine();

        using (FileStream fileStream = new FileStream(fileName, FileMode.Create))
        {
            if (Clipboard.ContainsData(System.Windows.DataFormats.EnhancedMetafile))
            {
                Metafile metafile = Clipboard.GetData(System.Windows.DataFormats.EnhancedMetafile) as Metafile;
                metafile.Save(fileName);
            }
            else if (Clipboard.ContainsData(System.Windows.DataFormats.Bitmap))
            {
                BitmapSource bitmapSource = Clipboard.GetData(System.Windows.DataFormats.Bitmap) as BitmapSource;

                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.QualityLevel = 100;
                encoder.Save(fileStream);
            }
        }
        object objFalse = false;

        wkb.Close(objFalse, Type.Missing, Type.Missing);
        excel.Quit();
    }
Example #9
0
        public void ExportRangeAsJpg()
        {
            Excel.Application xl;

            xl = (Excel.Application)ios.Marshal.GetActiveObject("Excel.Application");

            if (xl == null)
            {
                MessageBox.Show("No Excel !!");
                return;
            }

            Excel.Workbook wb = xl.ActiveWorkbook;
            Excel.Range    r  = wb.ActiveSheet.Range["A1:E10"];
            r.CopyPicture(Excel.XlPictureAppearance.xlScreen,
                          Excel.XlCopyPictureFormat.xlBitmap);

            if (Clipboard.GetDataObject() != null)
            {
                IDataObject data = Clipboard.GetDataObject();

                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    Image image = (Image)data.GetData(DataFormats.Bitmap, true);
                    this.pict1.Image = image;
                    image.Save(@"C:\_Stuff\test\sample.jpg",
                               System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                else
                {
                    MessageBox.Show("No image in Clipboard !!");
                }
            }
            else
            {
                MessageBox.Show("Clipboard Empty !!");
            }
        }
Example #10
0
        public IntPtr GetHemf()
        {
            AssertNotDisposed();
            Excel.Range _range = _GetRange();
            var         hEmf   = IntPtr.Zero;

            lock (Synchronization.ClipboardSyncRoot)
            {
                _range.CopyPicture(Excel.XlPictureAppearance.xlScreen, Excel.XlCopyPictureFormat.xlPicture);
                if (UnmanagedClipboard.OpenClipboard(ProcessFunctions.MainWindowHandle))
                {
                    if (UnmanagedClipboard.IsClipboardFormatAvailable(CF_ETAFILE) != 0)
                    {
                        hEmf = UnmanagedClipboard.GetClipboardData(CF_ETAFILE);
                    }

                    UnmanagedClipboard.CloseClipboard();
                }
            }

            Marshal.ReleaseComObject(_range);
            return(hEmf);
        }
Example #11
0
        // Create a new schedule
        public ViewSchedule CreateSchedule(string filePath, UIDocument uidoc)
        {
            ViewSchedule sched = null;

            _doc = uidoc.Document;

            if (uidoc.Document.IsWorkshared)
            {
                docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(uidoc.Document.GetWorksharingCentralModelPath());
            }
            else
            {
                docPath = uidoc.Document.PathName;
            }


            excelFilePath = filePath;
            if (File.Exists(excelFilePath))
            {
                // read the Excel file and create the schedule
                Excel.Application excelApp   = new Excel.Application();
                Excel.Workbook    workbook   = excelApp.Workbooks.Open(excelFilePath, ReadOnly: true);
                Excel.Sheets      worksheets = workbook.Worksheets;

                List <WorksheetObject> worksheetObjs = new List <WorksheetObject>();
                foreach (Excel.Worksheet ws in worksheets)
                {
                    WorksheetObject wo   = new WorksheetObject();
                    string          name = ws.Name;
                    wo.Name = name;
                    Excel.Range range = ws.UsedRange;
                    try
                    {
                        range.CopyPicture(Excel.XlPictureAppearance.xlPrinter, Excel.XlCopyPictureFormat.xlBitmap);
                        if (Clipboard.GetDataObject() != null)
                        {
                            IDataObject data = Clipboard.GetDataObject();
                            if (data.GetDataPresent(DataFormats.Bitmap))
                            {
                                System.Drawing.Image img = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
                                wo.Image = img;
                            }
                        }
                    }
                    catch { }
                    worksheetObjs.Add(wo);
                }

                // Pop up the worksheet form
                WorksheetSelectForm wsForm = new WorksheetSelectForm(worksheetObjs, this, _doc);


                // Revit version
                int version = Convert.ToInt32(uidoc.Application.Application.VersionNumber);

                // Get the Revit window handle
                IntPtr handle = IntPtr.Zero;
                if (version < 2019)
                {
                    handle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
                }
                else
                {
                    handle = uidoc.Application.GetType().GetProperty("MainWindowHandle") != null
                        ? (IntPtr)uidoc.Application.GetType().GetProperty("MainWindowHandle").GetValue(uidoc.Application)
                        : IntPtr.Zero;
                }
                System.Windows.Interop.WindowInteropHelper wih = new System.Windows.Interop.WindowInteropHelper(wsForm)
                {
                    Owner = handle
                };

                //Show the Worksheet Select form
                wsForm.ShowDialog();
                if (wsForm.DialogResult.HasValue && wsForm.DialogResult.Value)
                {
                    foreach (Excel.Worksheet ws in worksheets)
                    {
                        if (ws.Name == selectedWorksheet.Name)
                        {
                            worksheet = ws;
                            break;
                        }
                    }
                }
                else
                {
                    worksheet = null;
                }

                if (worksheet != null)
                {
                    workSheetName = worksheet.Name;
                    Transaction trans = new Transaction(_doc, "Create Schedule");
                    trans.Start();

                    // Create the schedule
                    sched      = ViewSchedule.CreateSchedule(_doc, new ElementId(-1));
                    sched.Name = worksheet.Name;

                    // Add a single parameter for data, Assembly Code
                    ElementId       assemblyCodeId = new ElementId(BuiltInParameter.UNIFORMAT_DESCRIPTION);
                    ScheduleFieldId fieldId        = null;
                    foreach (SchedulableField sField in sched.Definition.GetSchedulableFields())
                    {
                        ElementId paramId = sField.ParameterId;

                        if (paramId == assemblyCodeId)
                        {
                            ScheduleField field = sched.Definition.AddField(sField);
                            fieldId = field.FieldId;
                            break;
                        }
                    }

                    if (fieldId != null && sched.Definition.GetFieldCount() > 0)
                    {
                        ScheduleDefinition schedDef = sched.Definition;

                        // Add filters to hide all elements in the schedule, ie make sure nothing shows up in the body.
                        ScheduleFilter filter0 = new ScheduleFilter(fieldId, ScheduleFilterType.Equal, "NO VALUES FOUND");
                        ScheduleFilter filter1 = new ScheduleFilter(fieldId, ScheduleFilterType.Equal, "ALL VALUES FOUND");
                        schedDef.AddFilter(filter0);
                        schedDef.AddFilter(filter1);

                        // Turn off the headers
                        schedDef.ShowHeaders = false;

                        // Fill out the schedule from Excel data
                        AddScheduleData(filePath, sched, _doc, PathType.Absolute, false);
                    }



                    if (linkFile)
                    {
                        AssignSchemaData(sched.Id, workSheetName, _doc);
                    }

                    trans.Commit();
                }

                //workbook.Close();
                workbook.Close(false);
                Marshal.ReleaseComObject(worksheets);
                if (worksheet != null)
                {
                    Marshal.ReleaseComObject(worksheet);
                }
                Marshal.ReleaseComObject(workbook);
                excelApp.Quit();
                Marshal.ReleaseComObject(excelApp);
            }
            return(sched);
        }
        private void ReloadFromButton_Click(object sender, RoutedEventArgs e)
        {
            //DataRowView selectedRow = (DataRowView)linkDataGrid.SelectedItems[0];
            LinkData selectedRow = (LinkData)linkDataGrid.SelectedItems[0];

            if (selectedRow != null)
            {
                // Find an Excel File
                System.Windows.Forms.OpenFileDialog openDlg = new System.Windows.Forms.OpenFileDialog()
                {
                    Title            = "Reload From an Excel File",
                    Filter           = "Excel Files (*.xls; *.xlsx)|*.xls;*.xlsx",
                    RestoreDirectory = true
                };


                System.Windows.Forms.DialogResult result = openDlg.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string excelFilePath = openDlg.FileName;

                    if (System.IO.File.Exists(excelFilePath))
                    {
                        // read the Excel file and create the schedule
                        Excel.Application excelApp     = new Excel.Application();
                        Excel.Workbook    workbook     = excelApp.Workbooks.Open(excelFilePath);
                        Excel.Sheets      wbWorksheets = workbook.Worksheets;

                        List <WorksheetObject> worksheetObjs = new List <WorksheetObject>();
                        foreach (Excel.Worksheet ws in wbWorksheets)
                        {
                            WorksheetObject wo   = new WorksheetObject();
                            string          name = ws.Name;
                            wo.Name = name;
                            Excel.Range range = ws.UsedRange;
                            try
                            {
                                range.CopyPicture(Excel.XlPictureAppearance.xlPrinter, Excel.XlCopyPictureFormat.xlBitmap);
                                if (Clipboard.GetDataObject() != null)
                                {
                                    IDataObject data = Clipboard.GetDataObject();
                                    if (data.GetDataPresent(DataFormats.Bitmap))
                                    {
                                        System.Drawing.Image img = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
                                        wo.Image = img;
                                    }
                                }
                            }
                            catch { }
                            worksheetObjs.Add(wo);
                        }

                        // Pop up the worksheet form
                        WorksheetSelectForm wsForm = new WorksheetSelectForm(worksheetObjs, this, doc);
                        wsForm.ShowDialog();

                        if (wsForm.DialogResult.HasValue && wsForm.DialogResult.Value)
                        {
                            for (int i = 0; i < elementIds.Count; i++)
                            {
                                try
                                {
                                    int intValue = selectedRow.ElementId;
                                    if (elementIds[i].IntegerValue == intValue)
                                    {
                                        // read and reload the file.
                                        Scheduler creator = new Scheduler();
                                        creator.ModifySchedule(doc, elementIds[i], excelFilePath, worksheetObj.Name, "Reload Excel Schedule", pathTypes[i], contentOnly);
                                        string docPath;
                                        if (doc.IsWorkshared)
                                        {
                                            docPath = ModelPathUtils.ConvertModelPathToUserVisiblePath(doc.GetWorksharingCentralModelPath());
                                        }
                                        else
                                        {
                                            docPath = doc.PathName;
                                        }

                                        if ((PathType)pathTypes[i] == PathType.Relative)
                                        {
                                            paths[i] = PathExchange.GetRelativePath(excelFilePath, docPath);
                                        }
                                        else
                                        {
                                            paths[i] = excelFilePath;
                                        }

                                        worksheets[i] = worksheetObj.Name;
                                        System.IO.FileInfo fi = new System.IO.FileInfo(excelFilePath);
                                        dateTimes[i] = fi.LastWriteTimeUtc.ToString();

                                        // Read the schema information
                                        Autodesk.Revit.DB.ExtensibleStorage.Schema schema = Autodesk.Revit.DB.ExtensibleStorage.Schema.Lookup(schemaGuid);
                                        if (schema != null)
                                        {
                                            Autodesk.Revit.DB.ExtensibleStorage.Entity entity = null;
                                            DataStorage ds = SchemaManager.GetDataStorage(doc);
                                            try
                                            {
                                                entity = ds.GetEntity(schema);
                                            }
                                            catch { }

                                            if (entity != null)
                                            {
                                                Transaction trans = new Transaction(doc, "Update Excel Document");
                                                trans.Start();
                                                entity.Set <IList <string> >("ExcelFilePath", paths);
                                                entity.Set <IList <string> >("WorksheetName", worksheets);
                                                entity.Set <IList <string> >("DateTime", dateTimes);
                                                entity.Set <IList <int> >("PathType", pathTypes);
                                                ds.SetEntity(entity);
                                                trans.Commit();

                                                BuildTable();
                                            }
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                        try
                        {
                            workbook.Close();
                            Marshal.ReleaseComObject(worksheets);
                            //Marshal.ReleaseComObject(worksheet);
                            Marshal.ReleaseComObject(workbook);
                            excelApp.Quit();
                            Marshal.ReleaseComObject(excelApp);
                        }
                        catch { }
                    }
                }
            }
        }