To begin using Excel from C# we should right-click on References in Solution Explorer or Project/Add Reference on File Menu and add a Reference to Excel (Microsoft Excel Object Library 12.0)
The following methods are not fully mine, they are the modification of code, taken from Internet.
1. Example of opening a definite Worksheet for future use.
Let’s assume that you have AAA.xls file previously created on C:\.
// Some additional namespaces
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
// Common variables for different methods
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
private void OpenExcelWorksheet()
{
object misValue = System.Reflection.Missing.Value;
// Specify a "currently active folder"
string activeDir = @"c:\";
//Create a newPath - the Path to Excel file
string newPath = System.IO.Path.Combine(activeDir, "AAA");
// Create the subfolder
// System.IO.Directory.CreateDirectory(newPath);
// Create a new file name.
string newFileName = "AAA.xls";
// Combine the new file name with the path
newPath = System.IO.Path.Combine(newPath, newFileName);
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(newPath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
2. Inserting data to Excel Worksheet
The following method inserts data in 2 column array “citations” to Excel worksheet to the lines from fromNum to toNum and columns B and C.
private void InsertToExcel(int fromNum, int toNum)
{
string fromRange, toRange;
fromRange = "B" + fromNum.ToString();
toRange = "C" + toNum.ToString();
try
{
xlApp.Visible = true;
//Fill A1:B20 with an array of values (First and Last Names).
xlWorkSheet.get_Range(fromRange, toRange).Value2 = citations;
//Make sure Excel is visible and give the user control
//of Microsoft Excel's lifetime.
xlApp.Visible = true;
xlApp.UserControl = true;
}
catch (Exception theException)
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat(errorMessage, theException.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, theException.Source);
MessageBox.Show(errorMessage, "Error");
}
}
References: