List of Exercises

Create Excel Viewer in WinForms C#

	    
private void openFile_Click(object sender, EventArgs e)
    {
      OpenFileDialog opf = new OpenFileDialog();
      opf.Filter = "Excel File|*.xlsx|Excel 2007|*.xls";
      if (opf.ShowDialog() == DialogResult.OK)
      {
        xlView1.showFile(opf.FileName);
      }
    }


		//========================XLView.cs========================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Excel_Viewer
{
  public partial class XLView : UserControl
  {
    WebBrowser webBrowser1;
    Microsoft.Office.Interop.Excel.Application excel;
    public XLView()
    {
      InitializeComponent();
    }
    public void showFile(string fileName)
    {
      if (fileName != "")
      {
        excel = new Microsoft.Office.Interop.Excel.Application();
        excel.Visible = false;
        Microsoft.Office.Interop.Excel.Workbook xlWorkbook = excel.Workbooks.Open(fileName);
        var xlWorksheet = xlWorkbook.Sheets[1];
        var tempFileName = GetTempFile("html");
        object missing = System.Reflection.Missing.Value;
        object newFileName = (object)tempFileName;
        object fileType = (object)Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;

        xlWorkbook.SaveAs(tempFileName, fileType, missing, missing, missing, missing,
           Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
           missing, missing, missing, missing, missing);
        webBrowser1 = new WebBrowser();
        webBrowser1.DocumentCompleted+=webBrowser1_DocumentCompleted;
        webBrowser1.Dock = DockStyle.Fill;
        webBrowser1.Navigate(tempFileName);
        this.Controls.Clear();
        this.Controls.Add(webBrowser1);
      }
    }
    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
      string tmpFile = "";
      try
      {
        if (tmpFile != string.Empty)
        {
          // delete the temp file we created.
          File.Delete(tmpFile);

          // set the tempFileName to an empty string.
          tmpFile = string.Empty;
        }
      }
      catch (Exception ex)
      {
      }
    }

    private string GetTempFile(string extension)
    {
      // Uses the Combine, GetTempPath, ChangeExtension,
      // and GetRandomFile methods of Path to
      // create a temp file of the extension we're looking for.
      return Path.Combine(Path.GetTempPath(),
        Path.ChangeExtension(Path.GetRandomFileName(), extension));
    }
  }
}
		
	 



Download the project of Visual Studio 2013 in DropBox Download


How to Create Excel Viewer in Winforms C# | Read Excel File and View


Video Thumbnail