How to Set Excel Sheet Zoom Percentage using C#

If you are automating excel using C# and Microsoft.Office.Interop and you need to set the zoom factor of excel sheet, first you need to activate that particular sheet then set the zoom percentage of ActiveWindow.Zoom property of excel application object to your desired number.

 Here in this blog, you will get step by step sample code of setting zoom percentage of “Sheet1” to 70 .

Step 1: Add the Excel reference to your Class by placing this code in the list of namespaces.

using excel = Microsoft.Office.Interop.Excel;

Step 2: Define the function with the name you desire. Here we defined the function with the name excelZoomSetExample.

public void excelZoomSetExample()
{

}

Step 3: Write the code inside the function as given below. I have added comments above each line of code that will help you understand the functionality of each line.

public void excelZoomSetExample()
{
  // creates excel application object
 Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application(); 
  // creates new excel workbook object
  Microsoft.Office.Interop.Excel.Workbook excelworkBook;
  // creates new excel sheet object
  Microsoft.Office.Interop.Excel.Worksheet excelSheet;
  string excelPath = "D:/Test Excel";
  // opens excel workbook on the specified path
  objExcel.Workbooks.Open(excelPath);
  // assigns the workbook to excel application
  excelworkBook = objExcel.Workbooks[1];
  // specifies the sheet to work on
  excelSheet = (excel.Worksheet)excelworkBook.Sheets.get_Item("Sheet1");
  //Activates the Sheet1
  excelSheet.Activate();
  //sets the zoom percentage to 70
  objExcel.ActiveWindow.Zoom = 70;
  // saves the excel on specified path
  excelworkBook.SaveAs("D:\\Zoom Example Excel.xlsx");
  // closes all workbooks
  objExcel.Workbooks.Close();
  // quits the excel application object
  objExcel.Quit();
  
  
}

Now you have got output excel workbook saved in D drive with name “Zoom Example Excel.xlsx”. Just open this and check, you will find that zoom percentage of “Sheet1” is set 70.

Leave a Reply