Vista previa de archivos de Word/Excel en el Explorador de archivos sin MS Office

Vista previa de archivos de Word/Excel en el Explorador de archivos sin MS Office

Soy profesor en una universidad, nos vemos obligados a usar WPS Office ya que el instituto no puede cubrir los gastos de MS Office, por lo que hemos perdido la función predeterminada en Windows para obtener una vista previa de los archivos de Word/Excel después de activar el panel de vista previa en Archivos de Windows. Explorador. Los últimos 2 días pasé buscando algún explorador de archivos alternativo, pero incluso si algún proveedor afirma que la vista previa no está disponible para documentos de Office o no tiene ninguna función de vista previa.

Los profesores necesitan con urgencia la vista previa, ya que a menudo revisamos muchos archivos de Word, simplemente haciendo clic en ellos en el explorador de archivos de Windows o usando las teclas de flecha para navegar.

Por favor sugiera alguna solución funcional.

Respuesta1

Como puedo desarrollar aplicaciones winforms, me esforcé mucho con varias soluciones.

La mayoría de ellos no eran gratuitos, por lo que no se podían utilizar, pero Pandoc Converter me ayudó, pero no era muy bueno.

Así que me pasé a la edición comunitaria Syncfusion, ya es gratuita y sus bibliotecas permiten convertir todos los formatos principales basados ​​en procesadores de texto y su resultado fue el mismo que el de otras soluciones no gratuitas. Estoy compartiendo la fuente aquí si alguien lo necesita (es un archivo con el código subyacente de Winforms) y permite obtener una vista previa de todos los formatos principales basados ​​en procesamiento de textos (.doc, .docx, .rtf, .dot, .odt), no los formatos Excel o ppt. compatible, pero cualquiera puede ampliarlo para incluirlos también

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using Microsoft.VisualBasic.FileIO;
using Syncfusion.DocIO;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocToPDFConverter;
using Syncfusion.OfficeChart;
using Syncfusion.OfficeChartToImageConverter;
using Syncfusion.Pdf;
using NPOI;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace DocPreViewerNew
{
    public partial class Form1 : Form
    {
        public ChromiumWebBrowser wb;
        List<string> AllFiles = new List<string>();
        List<string> AllNamesOnly = new List<string>();
        string SelectedFile;
        string NameOnly;
        int ResizeUnit = 40;
        string[] SourcePath;
        int PDFZoomUnit = 100;
        string XLPath = "";

        public Form1()
        {
            InitializeComponent();
            InitializeChromium();            
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.KeyPreview = true;
            //lbFiles.Width = Convert.ToInt32(this.Width * 0.23);
            //panel2.Location = new Point(lbFiles.Location.X +Convert.ToInt32(this.Width * 0.23)+5, panel2.Location.Y);
            //panel2.Width = Convert.ToInt32(this.Width*0.75);

            if (Properties.Settings.Default.PreviewMode.Equals("HTML")) rbHTML.Checked = true;
            else rbPDF.Checked = true;

            PDFZoomUnit = Convert.ToInt32(txtPDFZoom.Text.Trim());

           
        }

        private void lbFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {               
                PDFZoomUnit = Convert.ToInt32(txtPDFZoom.Text.Trim());
                wb.LoadUrl("about:blank"); lblFCount.Text = "";
                if (lbFiles.SelectedIndices.Count == 1)
                {
                    // Two string lists
                    SelectedFile = AllFiles[lbFiles.SelectedIndex];
                    NameOnly = AllNamesOnly[lbFiles.SelectedIndex];
                    lblFCount.Text = "File No: " + (lbFiles.SelectedIndex+1).ToString();

                    if (NameOnly.EndsWith(".docx") || NameOnly.EndsWith(".doc") || NameOnly.EndsWith(".rtf"))
                    {
                        //Loads the template document
                        WordDocument document = new WordDocument(SelectedFile, FormatType.Automatic);

                        if (rbHTML.Checked == true)
                        {
                            //Saves the document as Html file
                            document.Save(Environment.CurrentDirectory + "\\" + "output.html", FormatType.Html);
                            wb.LoadUrl(Environment.CurrentDirectory + "\\" + "output.html");
                        }
                        else
                        {
                            //Initializes the ChartToImageConverter for converting charts during Word to pdf conversion
                            document.ChartToImageConverter = new ChartToImageConverter();
                            //Sets the scaling mode for charts (Normal mode reduces the Pdf file size)
                            document.ChartToImageConverter.ScalingMode = ScalingMode.Normal;
                            //Creates an instance of the DocToPDFConverter - responsible for Word to PDF conversion
                            DocToPDFConverter converter = new DocToPDFConverter();
                            //Sets true to enable the fast rendering using direct PDF conversion.
                            converter.Settings.EnableFastRendering = true;
                            //Converts Word document into PDF document
                            PdfDocument pdfDocument = converter.ConvertToPDF(document);
                            //Saves the PDF file to file system
                            pdfDocument.Save(Environment.CurrentDirectory + "\\" + "output.pdf");
                            //Closes the instance of document objects
                            wb.LoadUrl(Environment.CurrentDirectory + "\\" + "output.pdf#zoom=" + PDFZoomUnit.ToString() + "&toolbar=0");
                            pdfDocument.Close(true);
                            //Closes the document 
                            document.Close();
                        }
                    }
                    else if (NameOnly.EndsWith(".pdf"))
                    {
                        wb.LoadUrl(SelectedFile + "#zoom=" + PDFZoomUnit.ToString() + "&toolbar=0");
                    }
                    else if (NameOnly.EndsWith(".txt"))
                        wb.LoadUrl(SelectedFile);
                    else
                    {
                        File.WriteAllText(Environment.CurrentDirectory + "\\" + "error1.html", "<h3>** Some Error **</h3><h4>Format not supported</h4>");
                        wb.LoadUrl(Environment.CurrentDirectory + "\\" + "error1.html");
                    }

                }
                else if (lbFiles.SelectedIndices.Count > 1)
                {
                    lblFCount.Text = "Total Selected: " + lbFiles.SelectedIndices.Count.ToString();
                }
            }
            catch(Exception ex)
            {
                File.WriteAllText(Environment.CurrentDirectory + "\\" + "error1.html", "<h3>** Some Error **</h3><h4>" + ex.Message + "</h4>");
                wb.LoadUrl(Environment.CurrentDirectory + "\\" + "error1.html");
            }

        }

        private void btnMoveSelected_Click(object sender, EventArgs e)
        {
           
        }



        //********
        #region UtilityFuntions


        private void lbFiles_DoubleClick(object sender, EventArgs e)
        {
            StartMaximized(AllFiles[lbFiles.SelectedIndex]);
        }

        private void lbFiles_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                StartMaximized(AllFiles[lbFiles.SelectedIndex]);
            else if (e.KeyCode == Keys.Delete)
            {
                try
                {
                    if (lbFiles.SelectedIndex != -1)
                    {
                        var confirmResult = MessageBox.Show("Are you sure to delete this item ??", "Confirm Delete!!", MessageBoxButtons.YesNo);

                        if (confirmResult == DialogResult.Yes)
                        {
                            wb.LoadUrl("about:blank");
                            FileSystem.DeleteFile(AllFiles[lbFiles.SelectedIndex], UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                            AllFiles.RemoveAt(lbFiles.SelectedIndex);
                            AllNamesOnly.RemoveAt(lbFiles.SelectedIndex);
                            lbFiles.SelectedIndexChanged -= lbFiles_SelectedIndexChanged;
                            lbFiles.Items.RemoveAt(lbFiles.SelectedIndex);
                            lbFiles.SelectedIndexChanged += lbFiles_SelectedIndexChanged;
                        }
                    }
                }
                catch (OperationCanceledException) { }
            }
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                RefreshEveryThing();
                btnXL.Enabled = true; btnMarks.Enabled = false;
                SourcePath = (string[])e.Data.GetData(DataFormats.FileDrop, false);
                

                if (SourcePath.Length == 1)
                {
                    XLPath = "";
                    AllFiles = Directory.GetFiles(SourcePath[0]).ToList();
                    string tmp = "";

                    foreach (string f in AllFiles)
                    {
                        tmp = f.Substring(f.LastIndexOf(@"\") + 1);
                        AllNamesOnly.Add(tmp);
                        lbFiles.Items.Add(tmp);
                    }
                    lbFiles.Sorted = true;

                    XLPath = SourcePath[0];
                }

            }
            catch { }
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
            else
                e.Effect = DragDropEffects.None;
        }


        private void StartMaximized(string FullFileName)
        {
            Process P = new Process();
            P.StartInfo.UseShellExecute = true;
            P.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
            P.StartInfo.FileName = FullFileName;
            P.Start();
        }

        private void Sleeep(int s)
        {
            Thread.Sleep(TimeSpan.FromSeconds(s));
        }

        
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();

            if (rbPDF.Checked == true) Properties.Settings.Default.PreviewMode = "PDF";
            else Properties.Settings.Default.PreviewMode = "HTML";
            Properties.Settings.Default.Save();
        }

        private void btnDec_Click(object sender, EventArgs e)
        {
            Point p = panel2.Location;
            lbFiles.Width -= ResizeUnit;
            panel2.Location = new Point(p.X - ResizeUnit, p.Y);
            //lblFCount.Location = new Point(p.X - ResizeUnit, lbFiles.Location.Y);
            panel2.Width += ResizeUnit;

        }

        private void btnInc_Click(object sender, EventArgs e)
        {
            Point p = panel2.Location;
            lbFiles.Width += ResizeUnit;
            panel2.Location = new Point(p.X + ResizeUnit, p.Y);
            //lblFCount.Location = new Point(p.X + ResizeUnit, lbFiles.Location.Y);
            panel2.Width -= ResizeUnit;
        }

        private void RefreshEveryThing()
        {
            try
            {
                AllFiles.Clear();
                AllNamesOnly.Clear();
                lbFiles.Items.Clear();
                SourcePath = null;
                SelectedFile = "";
                NameOnly = "";

                wb.LoadUrl("about:blank");

                if (File.Exists(Environment.CurrentDirectory + "\\" + "output.html"))
                FileSystem.DeleteFile(Environment.CurrentDirectory + "\\" + "output.html", UIOption.OnlyErrorDialogs, RecycleOption.DeletePermanently);

                if (File.Exists(Environment.CurrentDirectory + "\\" + "output.pdf"))
                    FileSystem.DeleteFile(Environment.CurrentDirectory + "\\" + "output.pdf", UIOption.OnlyErrorDialogs, RecycleOption.DeletePermanently);

                //if (SourcePath!=null && SourcePath.Length == 1)
                //{
                //    AllFiles = Directory.GetFiles(SourcePath[0]).ToList();
                //    string tmp = "";

                //    foreach (string f in AllFiles)
                //    {
                //        tmp = f.Substring(f.LastIndexOf(@"\") + 1);
                //        AllNamesOnly.Add(tmp);
                //        lbFiles.Items.Add(tmp);
                //    }
                //}
            }
            catch { }
        }

        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component
            wb = new ChromiumWebBrowser("");

            // Add it to the form and fill it to the form window.
            this.panel2.Controls.Add(wb);
            wb.Dock = DockStyle.Fill;
        }


        #endregion

        private void btnMarks_Click(object sender, EventArgs e)
        {
            if (lbFiles.SelectedIndex != -1)
            {
                Marks frmMarks = new Marks();
                frmMarks.ID = lbFiles.SelectedItem.ToString();
                frmMarks.XLFILE = XLPath;
                frmMarks.ShowDialog();

                if (frmMarks.MARKSENTERED == true)
                    lblFCount.Text = "Marks entered successfully";
                else
                    lblFCount.Text = "**Problem entering Marks**";

                frmMarks.Close();
            }
        }

        private void btnXL_Click(object sender, EventArgs e)
        {
            HSSFWorkbook hssfwb=null;
            
            try
            {
                if (Directory.Exists(SourcePath[0]))
                {
                    OpenFileDialog XL = new OpenFileDialog();
                    if (XLPath != String.Empty) XL.InitialDirectory = XLPath;
                    XL.Title = "Select Marks Sheet File";
                    XL.Filter = "Excel Files|*.xls;*.xlsx";
                    if (XL.ShowDialog() == DialogResult.OK) XLPath = XL.FileName;

                    //Check old Excel File
                    if (XLPath.EndsWith(".xls"))
                    {
                        using (FileStream file = new FileStream(XLPath, FileMode.Open, FileAccess.Read))
                        {
                            hssfwb = new HSSFWorkbook(file);
                            file.Close();
                        }

                        ISheet sheet = hssfwb.GetSheetAt(0);
                        try
                        {
                            if (sheet.GetRow(0).GetCell(0).StringCellValue != "StudentId" || sheet.GetRow(0).GetCell(1).StringCellValue != "Marks" || sheet.GetRow(0).GetCell(2).StringCellValue != "Comments")
                            {
                                MessageBox.Show("First sheet must have these three columns:\n\nStudentId  Marks  Comments");
                            }
                            else btnMarks.Enabled = true;
                        }
                        catch (NullReferenceException) { MessageBox.Show("First sheet must have these three columns:\n\nStudentId  Marks  Comments"); }
                    }                   
                }
            }
            catch { }
            finally
            {
                if (hssfwb!=null) hssfwb.Close();
                btnXL.Enabled = !btnMarks.Enabled;
            }

                       
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt && e.KeyCode == Keys.M)
            {
                btnMarks.PerformClick();
                //btncash_Click(null, null);
            }
        }
    } // Name space and class ends
}

información relacionada