Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Welcome again. I have a new project and for this I need to get SQL, Microsoft Office Excel and SQL work together. But first things first: We have to add some reference so we can use Excel in C#.
- Open a new project and select "Project" at the top, then click "add reference". In "Com" you will find "Microsoft Excel xx.x Object Library". Select it with a tick. Now we are ready to start a little code: */
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Excel = Microsoft.Office.Interop.Excel; //don't forget this, we need to add it. And for comfortability we define a short word
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- //some variables we need.
- Excel.Application xlApp = null; //the variable for the application itself. We initislize it with "null", so we can use the variable later and don't get errors
- Excel.Workbook xlWb; //something that defines all our Datasheets (the tables all together)
- Excel.Worksheet xlWs; //Something for a single worksheet (table)
- try
- {
- //initialisation for the Excel Process
- xlApp = new Excel.Application(); //an Object for our Excel-Application
- xlApp.Visible = true; //Or do you want an invisible back-ground excel in your taskmanager?^^
- xlApp.ScreenUpdating = true; //out Code will be slower, in a huge code we would see how the Cells fill up. Leave it false if you want to make it faster (But set it to true at the end of the code)
- //Define some things in Excel itself we need
- var myCount = xlApp.Workbooks.Count;
- xlWb = xlApp.Workbooks.Add(System.Reflection.Missing.Value);
- xlWs = xlWb.ActiveSheet;
- //That is it, at this point (+ catch and finally) we should have an exmpty Excel that opens and closes after we start the program
- /* Doing something with the cells is really simple, let's see some examples:
- This writes "Hello" into the Cell B3. First number is the column (numbers), the second one is the row (letters). Of course you can use variables for the numbers which you can use in Loops or something
- xlWs.Cells[3, 2] = "Hello";
- */
- }
- catch (Exception ex)
- {
- String myErrorMessage = ex.Message;
- Console.WriteLine(myErrorMessage);
- Console.ReadKey();
- }
- finally
- {
- /*End Excel. Be careful if you don't have this, Excel will be stuck in your Taskmanager (even when you close the Application) and cause weird Errors when you open it too often without noticing. I am talking out of experience ;) */
- if (xlApp != null)
- {
- xlApp.Quit();
- Console.ReadKey();
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment