- // Add NameSpace
- using Excel = Microsoft.Office.Interop.Excel;
- // Intialize the Excel
- object oMissing = System.Reflection.Missing.Value;
- Excel.Application xlApp = new Excel.Application();
- Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"" + txtFolderPath.Text + "/" + FileName);
- // Loop for excel worksheets
- for (int i = 1; i <= xlWorkbook.Worksheets.Count; i++)
- {
- // Access the excel worksheets
- Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[i];
- if (i == 1)
- {
- xlWorksheet.Name = "Executive Summary";
- xlWorksheet.Hyperlinks.Add(xlWorksheet.get_Range("A3", Type.Missing), string.Empty, "'Approver Report'!A1", Type.Missing, Type.Missing);
- xlWorksheet.Hyperlinks.Add(xlWorksheet.get_Range("A4", Type.Missing), string.Empty, "'Pending Approvals - SAP'!A1", Type.Missing, Type.Missing);
- xlWorksheet.Hyperlinks.Add(xlWorksheet.get_Range("A6", Type.Missing), string.Empty, "'Pending Approvals - Policy'!A1", Type.Missing, Type.Missing);
- }
- else if (i == 2)
- {
- xlWorksheet.Name = "Approver Report";
- xlWorksheet.Activate();
- xlWorksheet.Application.ActiveWindow.SplitRow = 3;
- xlWorksheet.Application.ActiveWindow.FreezePanes = true;
- xlWorksheet.get_Range("E1", Type.Missing).Font.Bold = true;
- xlWorksheet.Hyperlinks.Add(xlWorksheet.get_Range("E1", Type.Missing), string.Empty, "'Executive Summary'!A1", Type.Missing, Type.Missing);
- }
- else if (i == 3)
- {
- xlWorksheet.Name = "Pending Approvals - SAP";
- xlWorksheet.Activate();
- xlWorksheet.Application.ActiveWindow.SplitRow = 3;
- xlWorksheet.Application.ActiveWindow.FreezePanes = true;
- xlWorksheet.get_Range("G1", Type.Missing).Font.Bold = true;
- xlWorksheet.Hyperlinks.Add(xlWorksheet.get_Range("G1", Type.Missing), string.Empty, "'Executive Summary'!A1", Type.Missing, Type.Missing);
- }
- else if (i == 4)
- {
- xlWorksheet.Name = "Pending Approvals - Policy";
- xlWorksheet.Activate();
- xlWorksheet.Application.ActiveWindow.SplitRow = 3;
- xlWorksheet.Application.ActiveWindow.FreezePanes = true;
- xlWorksheet.get_Range("F1", Type.Missing).Font.Bold = true;
- xlWorksheet.Hyperlinks.Add(xlWorksheet.get_Range("F1", Type.Missing), string.Empty, "'Executive Summary'!A1", Type.Missing, Type.Missing);
- }
- }
- xlWorkbook.SaveAs(@"" + FilePath + "/" + FileName);
- // TO Stop the process
- var processes = from p in Process.GetProcessesByName("EXCEL")
- select p;
- foreach (var process in processes)
- {
- if (process.MainWindowTitle == "Microsoft Excel - " + fileD.Name)
- process.Kill();
- }
- }
- MessageBox.Show("Records rename successfully !", "Done");
In this code snippet, I write the code to read excel in c# and perform some tasks on excel.
