Friday, December 5, 2014

How to Edit an Excel File using C# with Excel Office Interop

Below is a simple example how to edit an Excel File using C# with Excel Office Interop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
 
namespace ExcelBlog
{
    class Program
    {
        static void Main(string[] args)
        {
            var xlApp = new Excel.Application();
            var xlWorkbook = xlApp.Workbooks.Open(
                @"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\in.xlsx");
            var xlWorksheet = xlWorkbook.Worksheets["Sheet1"];
            var fullRow = xlWorksheet.Rows.Count;
            var lastRow = xlWorksheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row;
            var dict = new Dictionary<string, IList<string>>();
            for (int i = 1; i <= lastRow; i++)
            {
                var cell = xlWorksheet.Cells[i, "A"].Value;
                xlWorksheet.Cells[i, "A"].Value = cell + "" + i;
            }
            xlWorkbook.SaveAs(@"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\out.xlsx");
            xlWorkbook.Close();
        }
    }
}