Excel and C# - EEMB DERSLER · 02.02.2011 · Developing Interactive Systems •Practical decision...

Preview:

Citation preview

Excel and C#

2

Overview

• Introduction to DatabaseSupport Systems

• Building a Web-Enabled Decision Support System

• Integrating DSS in Business Curriculum

3

Decision Support Systems (DSS)

• A decision support system is an information system that assists the user in decision-making.

Database

Model Base

GUI

User

Knowledge

Base

4

Developing Interactive Systems

• Practical decision making requires developing man-machine interactive systems.

The Model

Input

Data

Output,

Reports

User Interface,

Re-optimization

5

Development Process • Data Storage Mechanism

– MS Excel, Lotus – MS Access, Oracle, MS SQL Server, Dbase

• Data Manipulation – Visual C# for Applications (C#) – Visual C# .NET ( .NET) – Java, C/C++

• Data Presentation – VC#, .NET, MS Access, ASP .NET – Java Applets

6

Two Common Ways to Develop Databases

• Spreadsheet-Based Database Systems

– Spreadsheets

– Excel features

– C# for Excel

• Web-Enabled Database Systems

– Databases

– Microsoft Access

– .NET

– ADO .NET

7

Components of a Web-Enabled DSS

• Databases

• Database Management System (Access DBMS)

• Developing GUI

Users

Database

Application

DBMS

Database

8

Data Modeling

• Systematically converts E-R Diagram into

Relations

Portfolio

PID Name DateAdded

Stock

Company Symbol

PORTFOLIO STOCK

PID

Name Symbol

Company

Type DateAdded

Has

Quantity

Quantity Symbol PID

Portfolio

Details

Type

Object Data Model

Relational Data

Model

How to Create an Excel file in C#

• Create, Open or read an Excel file in C# , first you have to add the Microsoft Excel 14.0 Object Library in you project.

• First, the Excel assembly must be added to the project. To do this you must add a reference to the – Project -> Add Reference Microsoft. – Go to the .NET – Office.Interop.Excel library by going to the menu item. – Double click on it and press OK. – This adds the reference to your project. In the "using" section of

your code, type Microsoft.Office.Interop.Excel – using Microsoft.Office.Core; – using Excel = Microsoft.Office.Interop.Excel;

1. First we have to initialize the Excel application Object.

– Excel.Application xlApp = new

– Microsoft.Office.Interop.Excel.Application();

2. Before creating new Excel Workbook, you should check whether Excel is installed in your system.

if (xlApp == null)

{ MessageBox.Show("Excel is not properly installed!!"); return; }

3. Then create new Workbook

xlWorkBook = xlApp.Workbooks.Add(misValue);

4. After creating the new Workbook, next step is to write content to worksheet

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlWorkSheet.Cells[1, 1] = "ID"; xlWorkSheet.Cells[1, 2] = "Name"; xlWorkSheet.Cells[2, 1] = "1"; xlWorkSheet.Cells[2, 2] = "One"; xlWorkSheet.Cells[3, 1] = "2"; xlWorkSheet.Cells[3, 2] = "Two";

5. In the above code we write the data in the Sheet1, If you want to write data in sheet 2 then you should code like this..

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2); xlWorkSheet.Cells[1, 1] = "Sheet 2 content";

6. After write the content to the cell, next step is to save the excel file in your system.

xlWorkBook.SaveAs("your-file-name.xls");

Example of Creating Excel File

using System;

using System.Windows.Forms;

using System.Runtime.InteropServices;

using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsFormsApplication3

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();

if (xlApp == null)

{

MessageBox.Show("Excel is not properly installed!!");

return;

}

Excel.Workbook xlWorkBook;

Excel.Worksheet xlWorkSheet;

object misValue = System.Reflection.Missing.Value;

xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

xlWorkSheet.Cells[1, 1] = "ID";

xlWorkSheet.Cells[1, 2] = "Name";

xlWorkSheet.Cells[2, 1] = "1";

xlWorkSheet.Cells[2, 2] = "One";

xlWorkSheet.Cells[3, 1] = "2";

xlWorkSheet.Cells[3, 2] = "Two";

xlWorkBook.SaveAs("I:\\csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

xlWorkBook.Close(true, misValue, misValue);

xlApp.Quit();

Marshal.ReleaseComObject(xlWorkSheet);

Marshal.ReleaseComObject(xlWorkBook);

Marshal.ReleaseComObject(xlApp);

MessageBox.Show("Excel file created , you can find the file I:\\csharp-Excel.xls");

}

}

}

How to read an Excel file using C# • To access the object model from Visual C# .NET, you have to add

the Microsoft Excel 15.0 Object Library to you project. • After import the reference library, we have to initialize the Excel

application Object. – Excel.Application xlApp = new – Excel.Workbook xlWorkBook ; – Excel.Worksheet xlWorkSheet ; – Excel.Range range ;

• Next step is to open the Excel file and get the specified worksheet.

– xlApp = new Excel.Application(); – xlWorkBook = xlApp.Workbooks.Open(@"d:\csharp-Excel.xls", 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);

using System; using System.Windows.Forms; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsFormsApplication4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Excel.Application xlApp ; Excel.Workbook xlWorkBook ; Excel.Worksheet xlWorkSheet ; Excel.Range range ; string str; int rCnt ; int cCnt ; int rw = 0; int cl = 0;

xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(@"I:\csharp-Excel.xls", 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); range = xlWorkSheet.UsedRange; rw = range.Rows.Count; cl = range.Columns.Count; for (rCnt = 1; rCnt < = rw; rCnt++) { for (cCnt = 1; cCnt < = cl; cCnt++) { str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2; MessageBox.Show(str); } } xlWorkBook.Close(true, null, null); xlApp.Quit(); Marshal.ReleaseComObject(xlWorkSheet); Marshal.ReleaseComObject(xlWorkBook); Marshal.ReleaseComObject(xlApp); } } }

Update and Add Value

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Excel = Microsoft.Office.Interop.Excel; namespace WindowsFormsExcel02 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Excel.Application ExcelUygulama; Excel.Workbook ExcelProje; Excel.Worksheet ExcelSayfa; Excel.Range ExcelRange; object Missing = System.Reflection.Missing.Value; private void button3_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog(); // ExcelProje.SaveAs(save.FileName + ".xlsx", Excel.XlFileFormat.xlWorkbookDefault, Missing, Missing, false, Missing, Excel.XlSaveAsAccessMode.xlNoChange); ExcelProje.SaveAs("I:\\csharp-Excel" + ".xls", Excel.XlFileFormat.xlWorkbookDefault, Missing, Missing, false, Missing, Excel.XlSaveAsAccessMode.xlNoChange); ExcelProje.Close(true, Missing, Missing); ExcelUygulama.Quit(); MessageBox.Show("Excel Uygulamanız başarılı bir şekilde kaydedilmiştir."); }

private void button2_Click(object sender, EventArgs e)

{

textBox1.Clear();

textBox2.Clear();

textBox3.Clear();

}

private void button1_Click(object sender, EventArgs e)

{

Excel.Range veri = (Excel.Range)ExcelSayfa.Cells[Convert.ToInt32(textBox2.Text), Convert.ToInt32(textBox3.Text)];

veri.Value2 = textBox1.Text;

textBox1.Clear();

textBox2.Clear();

textBox3.Clear();

MessageBox.Show("Veri, belirttiğiniz hücreye yazılmıştır.");

}

private void Form1_Load(object sender, EventArgs e)

{

ExcelUygulama = new Excel.Application();

ExcelProje = ExcelUygulama.Workbooks.Add(Missing); //Yeni bir Excel Projesi oluşturalım.

ExcelSayfa = (Excel.Worksheet)ExcelProje.Worksheets.get_Item(1);//Yeni bir Sayfa oluşturalım. (Worksheet1, Worksheet2 dediğimiz olay...)

ExcelRange = ExcelSayfa.UsedRange; //Excelde kullanacağımız aralığı seçelim. (Hemen üstte ExcelSayfada Worksheet1'i seçtiğimizi görmelisiniz.)

ExcelSayfa = (Excel.Worksheet)ExcelUygulama.ActiveSheet; //Kullanacağımız Sayfayı (Worksheet1'i) ExcelSayfa değişkenine atayalım .

ExcelUygulama.Visible = false; //Excel uygulamamızı gizleyelim.

ExcelUygulama.AlertBeforeOverwriting = false; //Uygulamamıza veri girmeden önce verilen uyarıyı gizleyelim

}

}

}

Read and Import Excel File into DataSet

• We used Microsoft Excel 15.0 Object Library for read or write to and Excel file .

• In C# without using Excel Object we can insert, edit, delete, select etc.

• In cell content of an Excel file using OLEDB .

using System;

using System.Drawing;

using System.Windows.Forms;

Using System.Data.OleDb;

using Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

try

{

System.Data.OleDb.OleDbConnection MyConnection;

System.Data.DataTable DtSet;

System.Data.OleDb.OleDbDataAdapter MyCommand;

MyConnection = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\test.xlsx; Extended Properties='Excel 12.0 xml;HDR=YES;'");

MyCommand = new System.Data.OleDb.OleDbDataAdapter("SELECT * FROM [Sayfa1$]", MyConnection);

MyCommand.TableMappings.Add("Table", "TestTable");

DtSet = new System.Data.DataTable();

MyCommand.Fill(DtSet);

dataGridView1.DataSource = DtSet.DefaultView;

MyConnection.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

} }}

Recommended